text,length,is_long_context,metric_val,label_metric "class ZCL_WD_STATIC definition public final create public . *""* public components of class ZCL_WD_STATIC *""* do not include other source files here!!! public section. types: begin of ts_metadata, field type fieldname, visible(1), enabled(1), editable(1), required(1), end of ts_metadata . types: tt_metadata type table of ts_metadata . constants ICON_APPROVE type STRING value '~Icon/Approve' ##NO_TEXT. constants ICON_DELETE type STRING value '~Icon/Delete' ##NO_TEXT. constants ICON_FAILURE type STRING value '~Icon/Failure' ##NO_TEXT. constants ICON_GREEN_LED type STRING value '~Icon/GreenLed' ##NO_TEXT. constants ICON_RED_LED type STRING value '~Icon/RedLed' ##NO_TEXT. constants ICON_REFRESH type STRING value '~Icon/TbRefresh' ##NO_TEXT. constants ICON_YELLOW_LED type STRING value '~Icon/YellowLed' ##NO_TEXT. class-methods GET_URL importing !I_APP type SIMPLE !I_GUID type SIMPLE optional !I_LANGUAGE type LANGU default SY-LANGU !IT_PARAMETERS type TIHTTPNVP optional returning value(E_URL) type STRING . class-methods OPEN_URL importing !IR_CONTROLLER type ref to IF_WD_COMPONENT !I_URL type STRING . class-methods CLEAR_MESSAGES importing !IR_CONTROLLER type ref to IF_WD_COMPONENT . class-methods ADD_MESSAGE importing !IR_CONTROLLER type ref to IF_WD_COMPONENT !IS_MESSAGE type ZSMESSAGE optional . class-methods ADD_MESSAGES importing !IR_CONTROLLER type ref to IF_WD_COMPONENT optional !IT_MESSAGES type ZIMESSAGES . class-methods FILE_DOWNLOAD importing !I_FILE type SIMPLE !I_DATA type XSTRING . class-methods GET_PARAMETER importing !I_NAME type DATA returning value(E_VALUE) type STRING . class-methods GET_GUID returning value(E_GUID) type GUID . class-methods CREATE_USAGE importing !IR_CONTROLLER type ref to IF_WD_COMPONENT !I_COMPONENT type STRING !I_USAGE type STRING optional !I_REFRESH type ABAP_BOOL default ABAP_TRUE . class-methods CONF_WINDOW importing !IR_WINDOW type ref to IF_WD_WINDOW optional !IR_VIEW type ref to IF_WD_VIEW_CONTROLLER optional !I_WINDOW type SIMPLE optional !I_TITLE type SIMPLE optional !I_WIDTH type SIMPLE optional !I_HEIGHT type SIMPLE optional !I_BUTTON_KIND type WDR_POPUP_BUTTON_KIND default IF_WD_WINDOW=>CO_BUTTONS_NONE !I_ACTION_OK type SIMPLE optional !I_TEXT_OK type SIMPLE optional !I_ACTION_CANCEL type SIMPLE optional !I_TEXT_CANCEL type SIMPLE optional !I_ACTION_CLOSE type SIMPLE optional !I_ACTION_YES type SIMPLE optional !I_ACTION_NO type SIMPLE optional !I_FPM type ABAP_BOOL default ABAP_FALSE !I_OPEN type ABAP_BOOL default ABAP_TRUE !I_CLOSE type ABAP_BOOL default ABAP_TRUE . class-methods OPEN_WINDOW importing !IR_CONTROLLER type ref to IF_WD_COMPONENT !IR_VIEW type ref to IF_WD_VIEW_CONTROLLER optional !I_WINDOW type SIMPLE !I_TITLE type SIMPLE optional !I_BUTTON_KIND type WDR_POPUP_BUTTON_KIND default IF_WD_WINDOW=>CO_BUTTONS_NONE !I_ACTION_OK type SIMPLE optional !I_TEXT_OK type SIMPLE optional !I_ACTION_CANCEL type SIMPLE optional !I_TEXT_CANCEL type SIMPLE optional !I_ACTION_CLOSE type SIMPLE optional !I_ACTION_YES type SIMPLE optional !I_ACTION_NO type SIMPLE optional !I_OPEN type ABAP_BOOL default ABAP_TRUE !I_BUTTON_CLOSE type ABAP_BOOL default ABAP_TRUE !I_CLOSE type ABAP_BOOL default ABAP_TRUE !I_WIDTH type SIMPLE optional returning value(ER_WINDOW) type ref to IF_WD_WINDOW . class-methods OPEN_USAGE_WINDOW importing !IR_CONTROLLER type ref to IF_WD_COMPONENT !IR_VIEW type ref to IF_WD_VIEW_CONTROLLER optional !I_COMPONENT type SIMPLE optional !I_USAGE type SIMPLE optional !I_REFRESH type ABAP_BOOL default ABAP_TRUE !I_WINDOW type SIMPLE default 'W_MAIN' !I_TITLE type SIMPLE optional !I_BUTTON_KIND type WDR_POPUP_BUTTON_KIND default IF_WD_WINDOW=>CO_BUTTONS_NONE !I_ACTION_OK type SIMPLE optional !I_TEXT_OK type SIMPLE optional !I_ACTION_CANCEL type SIMPLE optional !I_TEXT_CANCEL type SIMPLE optional !I_ACTION_CLOSE type SIMPLE optional !I_ACTION_YES type SIMPLE optional !I_ACTION_NO type SIMPLE optional !I_OPEN type ABAP_BOOL default ABAP_TRUE !I_CLOSE type ABAP_BOOL default ABAP_TRUE returning value(ER_WINDOW) type ref to IF_WD_WINDOW . class-methods OPEN_CONFIRMATION_POPUP importing !IR_CONTROLLER type ref to IF_WD_COMPONENT !IR_VIEW type ref to IF_WD_VIEW_CONTROLLER optional !I_TITLE type SIMPLE optional !I_TEXT type SIMPLE !I_MESSAGE_TYPE type WDR_POPUP_MSG_TYPE default IF_WD_WINDOW=>CO_MSG_TYPE_NONE !I_BUTTON_KIND type WDR_POPUP_BUTTON_KIND default IF_WD_WINDOW=>CO_BUTTONS_OKCANCEL !I_ACTION_OK type STRING optional !I_ACTION_CANCEL type STRING optional !I_ACTION_YES type STRING optional !I_ACTION_NO type STRING optional !I_ACTION_CLOSE type STRING optional !I_OPEN type ABAP_BOOL default ABAP_TRUE returning value(ER_POPUP) type ref to IF_WD_WINDOW . class-methods OPEN_SEARCH_HELP importing !IR_CONTROLLER type ref to IF_WD_COMPONENT !IR_VIEW type ref to IF_WD_VIEW_CONTROLLER !I_SEARCH_HELP type SIMPLE !I_FIELD_NAME type SIMPLE !I_EVENT_HANDLER type SIMPLE !I_MULTI_SELECT type ABAP_BOOL default ABAP_FALSE raising ZCX_GENERIC . class-methods CLOSE importing !IR_VIEW type ref to IF_WD_VIEW_CONTROLLER !I_PLUG type SIMPLE default 'EXIT' . class-methods GET_ELEMENTS importing !IR_VIEW type ref to IF_WD_VIEW !I_NAME type SIMPLE default 'ROOTUIELEMENTCONTAINER' returning value(ET_ELEMENTS) type WDR_VIEW_ELEMENTS . class-methods SET_METADATA importing !IR_VIEW type ref to IF_WD_VIEW !IT_METADATA type TT_METADATA !I_READONLY type ABAP_BOOL default ABAP_FALSE . class-methods IS_CONFIG_MODE returning value(E_IS) type ABAP_BOOL . class-methods IS_PORTAL_MODE importing !IR_CONTROLLER type ref to IF_WD_COMPONENT returning value(E_IS) type ABAP_BOOL raising ZCX_GENERIC . class-methods IS_DEBUG_MODE returning value(E_IS) type ABAP_BOOL . protected section. *""* protected components of class ZCLSRM_WD *""* do not include other source files here!!! private section. *""* private components of class ZCL_WD_STATIC *""* do not include other source files here!!! ENDCLASS. CLASS ZCL_WD_STATIC IMPLEMENTATION. method add_message. data ls_message like is_message. if is_message is supplied. ls_message = is_message. else. move-corresponding sy to ls_message. endif. if ls_message-msgty ca 'AX'. ls_message-msgty = 'E'. endif. data lr_message_manager type ref to if_wd_message_manager. lr_message_manager = ir_controller->get_message_manager( ). lr_message_manager->report_t100_message( msgid = ls_message-msgid msgno = ls_message-msgno msgty = ls_message-msgty p1 = ls_message-msgv1 p2 = ls_message-msgv2 p3 = ls_message-msgv3 p4 = ls_message-msgv4 ). endmethod. method add_messages. data ls_message like line of it_messages. loop at it_messages into ls_message. add_message( ir_controller = ir_controller is_message = ls_message ). endloop. endmethod. method clear_messages. data lr_message_manager type ref to if_wd_message_manager. lr_message_manager = ir_controller->get_message_manager( ). lr_message_manager->clear_messages( ). endmethod. method close. data lr_controller type ref to if_wd_window_controller. lr_controller = ir_view->get_embedding_window_ctlr( ). data lr_window type ref to if_wd_window. lr_window = lr_controller->get_window( ). if lr_window is bound. lr_window->close( ). else. data lt_parameters type wdr_event_parameter_list. data ls_parameter like line of lt_parameters. ls_parameter-name = 'CLOSE_WINDOW'. create data ls_parameter-value type c. field-symbols type any. assign ls_parameter-value->* to . = abap_true. insert ls_parameter into table lt_parameters. data l_plug type string. l_plug = i_plug. lr_controller->if_wd_view_controller~fire_plug( plug_name = l_plug parameters = lt_parameters ). endif. endmethod. method conf_window. if ir_window is bound. data lr_window like ir_window. lr_window = ir_window. else. lr_window = ir_view->get_embedding_window( ). endif. if i_title is not initial. data l_title type string. l_title = i_title. lr_window->set_window_title( l_title ). endif. if i_width is not initial or i_height is not initial. data l_width type string. l_width = i_width. data l_height type string. l_height = i_height. lr_window->set_window_size( width = l_width height = l_height ). endif. if i_button_kind is not initial. lr_window->set_button_kind( i_button_kind ). endif. lr_window->set_close_in_any_case( i_close ). lr_window->set_window_position( position = if_wd_window=>co_center ). if i_action_ok is not initial. assert ir_view is bound. if i_fpm eq abap_true. data l_action type string. l_action = 'CONFIRM_ACTION'. *** data lt_event_mapping type /sapsrm/t_ch_wd_event_mapping. *** field-symbols like line of lt_event_mapping. *** append initial line to lt_event_mapping assigning . *** -action_name = 'ON_OK'. *** -event_name = i_action_ok. else. l_action = i_action_ok. endif. if i_text_ok is initial. data l_button_text type string. l_button_text = text-001. else. l_button_text = i_text_ok. endif. lr_window->subscribe_to_button_event( button = if_wd_window=>co_button_ok button_text = l_button_text action_name = l_action action_view = ir_view ). endif. if i_action_cancel is not initial. assert ir_view is bound. if i_fpm eq abap_true. l_action = 'CONFIRM_ACTION'. *** append initial line to lt_event_mapping assigning . *** -action_name = 'ON_OK'. *** -event_name = i_action_ok. else. l_action = i_action_cancel. endif. if i_text_cancel is initial. l_button_text = text-002. else. l_button_text = i_text_cancel. endif. lr_window->subscribe_to_button_event( button = if_wd_window=>co_button_cancel button_text = l_button_text action_name = i_action_cancel action_view = ir_view ). endif. if i_action_yes is not initial. assert ir_view is bound. lr_window->subscribe_to_button_event( button = if_wd_window=>co_button_yes action_name = i_action_yes action_view = ir_view ). endif. if i_action_no is not initial. assert ir_view is bound. lr_window->subscribe_to_button_event( button = if_wd_window=>co_button_no action_name = i_action_no action_view = ir_view ). endif. if i_action_close is not initial. assert ir_view is bound. lr_window->set_on_close_action( action_name = i_action_close view = ir_view ). endif. if i_fpm eq abap_true. *** ir_view->get_context( )->root_node->get_child_node( *** name = 'EVENT_MAPPING' )->bind_table( *** new_items = lt_event_mapping ). endif. endmethod. method create_usage. if i_usage is initial. data l_usage type string. l_usage = i_component. else. l_usage = i_usage. endif. if ir_controller->has_cmp_usage_group( i_component ) eq abap_false. data lr_group type ref to if_wd_component_usage_group. lr_group = ir_controller->create_cmp_usage_group( name = i_component used_component = l_usage ). else. if i_refresh eq abap_true. data ls_usage type wdapi_component_usage. ls_usage = ir_controller->get_component_usage( l_usage ). if ls_usage-component_usage->has_active_component( ) eq abap_true. ls_usage-component_usage->delete_component( ). endif. endif. endif. endmethod. method file_download. data l_file type string. l_file = i_file. cl_wd_runtime_services=>attach_file_to_response( i_filename = l_file i_mime_type = zcl_file_static=>get_mime( l_file ) i_content = i_data ). endmethod. method get_elements. data l_name type string. l_name = i_name. data lr_element like line of et_elements. lr_element ?= ir_view->get_element( l_name ). check lr_element is bound. insert lr_element into table et_elements. case lr_element->_definition_name. when 'TRANSPARENT_CONTAINER' or 'GROUP' or 'TRAY'. data lr_container type ref to cl_wd_uielement_container. lr_container ?= lr_element. data lt_elements like et_elements. lt_elements = lr_container->get_children( ). when 'PAGE_HEADER'. data lr_page_header type ref to cl_wd_page_header. lr_page_header ?= lr_element. data lt_page_areas type cl_wd_page_header_area=>tt_page_header_area. lt_page_areas = lr_page_header->get_areas( ). data lr_page_area like line of lt_page_areas. loop at lt_page_areas into lr_page_area. lr_element ?= lr_page_area. insert lr_element into table lt_elements. endloop. when 'PAGE_HEADER_AREA'. lr_page_area ?= lr_element. lr_element ?= lr_page_area->get_content( ). check lr_element is bound. insert lr_element into table lt_elements. when 'TABSTRIP'. data lr_tabstip type ref to cl_wd_tabstrip. lr_tabstip ?= lr_element. data lt_tabs type wd_tr_tab. lt_tabs = lr_tabstip->get_tabs( ). data lr_tab type ref to cl_wd_tab. loop at lt_tabs into lr_tab. lr_element ?= lr_tab->get_content( ). check lr_element is bound. insert lr_element into table lt_elements. endloop. when 'TOOLBAR'. data lr_toolbar type ref to cl_wd_toolbar. lr_toolbar ?= lr_element. data lt_toolbar_items type if_wd_toolbar_item=>tt_toolbar_item. lt_toolbar_items = lr_toolbar->get_toolbar_items( ). data lr_toolbar_item like line of lt_toolbar_items. loop at lt_toolbar_items into lr_toolbar_item. lr_element ?= lr_toolbar_item. insert lr_element into table lt_elements. endloop. when 'TOOLBAR_BTN_CHOICE'. data lr_toolbar_btn_choice type ref to cl_wd_toolbar_btn_choice. lr_toolbar_btn_choice ?= lr_element. data lt_choices type cl_wd_menu_action_item=>tt_menu_action_item. lt_choices = lr_toolbar_btn_choice->get_choices( ). data lr_choice like line of lt_choices. loop at lt_choices into lr_choice. lr_element ?= lr_choice. insert lr_element into table lt_elements. endloop. when others. return. endcase. loop at lt_elements into lr_element. l_name = lr_element->get_id( ). data lt_elements2 like et_elements. lt_elements2 = get_elements( ir_view = ir_view i_name = l_name ). insert lines of lt_elements2 into table et_elements. endloop. endmethod. method get_guid. e_guid = get_parameter( 'guid' ). endmethod. method get_parameter. data l_name type string. l_name = i_name. e_value = cl_wd_runtime_services=>get_url_parameter( l_name ). endmethod. method get_url. data l_app type string. l_app = i_app. data lt_parameters like it_parameters. lt_parameters = it_parameters. field-symbols like line of lt_parameters. read table lt_parameters transporting no fields with key name = 'sap-ui-language'. if sy-subrc ne 0. append initial line to lt_parameters assigning . -name = 'sap-ui-language'. -value = zcl_abap_static=>write( i_language ). endif. if i_guid is not initial. append initial line to lt_parameters assigning . -name = 'guid'. -value = i_guid. endif. call method cl_wd_utilities=>construct_wd_url exporting application_name = l_app in_parameters = lt_parameters importing out_absolute_url = e_url. endmethod. method is_config_mode. e_is = get_parameter( 'sap-config-mode' ). endmethod. method is_debug_mode. e_is = get_parameter( 'debug' ). endmethod. method is_portal_mode. data lr_manager type ref to if_wd_portal_integration. lr_manager = ir_controller->get_portal_manager( ). if lr_manager->m_portal_version is not initial. e_is = abap_true. endif. endmethod. method open_confirmation_popup. data lr_window_manager type ref to if_wd_window_manager. lr_window_manager = ir_controller->get_window_manager( ). data l_title type string. l_title = i_title. data l_text type string. l_text = i_text. data lt_text type string_table. insert l_text into table lt_text. er_popup = lr_window_manager->create_popup_to_confirm( text = lt_text button_kind = i_button_kind message_type = i_message_type window_title = l_title window_position = if_wd_window=>co_center ). if i_action_ok is not initial. assert ir_view is bound. er_popup->subscribe_to_button_event( exporting button = if_wd_window=>co_button_ok action_name = i_action_ok action_view = ir_view ). endif. if i_action_cancel is not initial. assert ir_view is bound. er_popup->subscribe_to_button_event( exporting button = if_wd_window=>co_button_cancel action_name = i_action_cancel action_view = ir_view ). endif. if i_action_yes is not initial. assert ir_view is bound. er_popup->subscribe_to_button_event( exporting button = if_wd_window=>co_button_yes action_name = i_action_yes action_view = ir_view ). endif. if i_action_no is not initial. assert ir_view is bound. er_popup->subscribe_to_button_event( exporting button = if_wd_window=>co_button_no action_name = i_action_no action_view = ir_view ). endif. if i_action_close is not initial. assert ir_view is bound. er_popup->set_on_close_action( exporting action_name = i_action_close view = ir_view ). endif. er_popup->set_window_position( position = if_wd_window=>co_center ). if i_open eq abap_true. er_popup->open( ). endif. endmethod. method open_search_help. data l_search_help type shlpname. l_search_help = i_search_help. data l_field_name type string. l_field_name = i_field_name. data l_event_handler type string. l_event_handler = i_event_handler. data lr_window_manager type ref to if_wd_window_manager. lr_window_manager = ir_controller->get_window_manager( ). try. lr_window_manager->open_value_help( view = ir_view event_handler = l_event_handler searchhelp = l_search_help fieldname = l_field_name multi_select = i_multi_select ). data lx_exception type ref to cx_wd_valuehelp. catch cx_wd_valuehelp into lx_exception. zcx_generic=>raise( i_text = lx_exception->get_text( ) ). endtry. endmethod. method open_url. check i_url is not initial. data lr_window_manager type ref to if_wd_window_manager. lr_window_manager ?= ir_controller->get_window_manager( ). data lr_window type ref to if_wd_window. lr_window = lr_window_manager->create_external_window( url = i_url ). lr_window->open( ). endmethod. method open_usage_window. if i_usage is initial. data l_usage type string. l_usage = i_component. else. l_usage = i_usage. endif. if i_component is not initial. create_usage( ir_controller = ir_controller i_component = i_component i_usage = l_usage i_refresh = i_refresh ). endif. data l_window type string. l_window = i_window. data lr_window_manager type ref to if_wd_window_manager. lr_window_manager = ir_controller->get_window_manager( ). er_window = lr_window_manager->create_window_for_cmp_usage( interface_view_name = l_window component_usage_name = l_usage message_display_mode = if_wd_window=>co_msg_display_mode_selected close_in_any_case = i_close is_resizable = abap_true ). conf_window( ir_window = er_window ir_view = ir_view i_title = i_title i_button_kind = i_button_kind i_action_ok = i_action_ok i_text_ok = i_text_ok i_action_cancel = i_action_cancel i_text_cancel = i_text_cancel i_action_close = i_action_close i_action_yes = i_action_yes i_action_no = i_action_no i_open = i_open i_close = i_close ). endmethod. method open_window. data lr_window_manager type ref to if_wd_window_manager. lr_window_manager = ir_controller->get_window_manager( ). data l_window type string. l_window = i_window. data l_title type string. l_title = i_title. er_window = lr_window_manager->create_window( window_name = l_window title = l_title is_resizable = abap_true message_display_mode = if_wd_window=>co_msg_display_mode_selected message_type = if_wd_window=>co_msg_type_none button_kind = i_button_kind close_button = i_button_close close_in_any_case = i_close ). conf_window( ir_window = er_window ir_view = ir_view i_title = i_title i_button_kind = i_button_kind i_action_ok = i_action_ok i_text_ok = i_text_ok i_action_cancel = i_action_cancel i_text_cancel = i_text_cancel i_action_close = i_action_close i_action_yes = i_action_yes i_action_no = i_action_no i_close = i_close i_width = i_width ). "" Open if i_open eq abap_true. er_window->open( ). endif. endmethod. method set_metadata. define set_visible. if &2-visible eq zcl_abap_static=>yes. &1->set_visible( 02 ). elseif &2-visible eq zcl_abap_static=>no. &1->set_visible( 01 ). endif. end-of-definition. define set_visible_boolean. if &2-visible eq zcl_abap_static=>yes. &1->set_visible( abap_true ). elseif &2-visible eq zcl_abap_static=>no. &1->set_visible( abap_false ). endif. end-of-definition. define set_enabled. if &2-enabled eq zcl_abap_static=>yes. &1->set_enabled( abap_true ). elseif &2-enabled eq zcl_abap_static=>no. &1->set_enabled( abap_false ). endif. end-of-definition. define set_editable. if &2-editable eq zcl_abap_static=>yes. &1->set_read_only( abap_false ). elseif &2-editable eq zcl_abap_static=>no. &1->set_read_only( abap_true ). endif. end-of-definition. define set_required. if &2-required = zcl_abap_static=>yes. &1->set_state( 1 ). elseif &2-required = zcl_abap_static=>no. &1->set_state( 0 ). endif. end-of-definition. define set_all. set_visible &1 &2. set_enabled &1 &2. set_editable &1 &2. set_required &1 &2. end-of-definition. "" Получаем элементы экрана data lt_elements type wdr_view_elements. lt_elements = zcl_wd_static=>get_elements( ir_view ). "" Обрабатываем элементы экрана в соответствии с метаданными data lr_element like line of lt_elements. loop at lt_elements into lr_element. data ls_metadata like line of it_metadata. clear ls_metadata. read table it_metadata into ls_metadata with key field = lr_element->id. check sy-subrc eq 0. if i_readonly eq abap_true. ls_metadata-editable = zcl_abap_static=>no. endif. if lr_element->_definition_name = 'LABEL'. data lr_label type ref to cl_wd_label. lr_label ?= lr_element. set_visible lr_label ls_metadata. set_enabled lr_label ls_metadata. elseif lr_element->_definition_name = 'INPUT_FIELD'. data lr_input_field type ref to cl_wd_input_field. lr_input_field ?= lr_element. set_all lr_input_field ls_metadata. elseif lr_element->_definition_name = 'TEXT_EDIT'. data lr_text_edit type ref to cl_wd_text_edit. lr_text_edit ?= lr_element. set_all lr_text_edit ls_metadata. elseif lr_element->_definition_name = 'DROPDOWN_BY_KEY'. data lr_dropkey type ref to cl_wd_dropdown_by_key. lr_dropkey ?= lr_element. set_all lr_dropkey ls_metadata. elseif lr_element->_definition_name = 'DROPDOWN_BY_IDX'. data lr_dropidx type ref to cl_wd_dropdown_by_idx. lr_dropidx ?= lr_element. set_all lr_dropidx ls_metadata. elseif lr_element->_definition_name = 'BUTTON'. data lr_button type ref to cl_wd_button. lr_button ?= lr_element. set_visible lr_button ls_metadata. set_enabled lr_button ls_metadata. elseif lr_element->_definition_name = 'TOOLBAR'. data lr_toolbar type ref to cl_wd_toolbar. lr_toolbar ?= lr_element. set_visible lr_toolbar ls_metadata. set_enabled lr_toolbar ls_metadata. elseif lr_element->_definition_name = 'TOOLBAR_BUTTON'. data lr_toolbar_button type ref to cl_wd_toolbar_button. lr_toolbar_button ?= lr_element. set_visible lr_toolbar_button ls_metadata. set_enabled lr_toolbar_button ls_metadata. elseif lr_element->_definition_name = 'TOOLBAR_BTN_CHOICE'. data lr_toolbar_btn_choice type ref to cl_wd_toolbar_btn_choice. lr_toolbar_btn_choice ?= lr_element. set_visible lr_toolbar_btn_choice ls_metadata. set_enabled lr_toolbar_btn_choice ls_metadata. elseif lr_element->_definition_name = 'MENU_ACTION_ITEM'. data lr_menu_action_item type ref to cl_wd_menu_item. lr_menu_action_item ?= lr_element. set_visible_boolean lr_menu_action_item ls_metadata. elseif lr_element->_definition_name = 'TRANSPARENT_CONTAINER'. data lr_container type ref to cl_wd_transparent_container. lr_container ?= lr_element. set_visible lr_container ls_metadata. set_enabled lr_container ls_metadata. elseif lr_element->_definition_name = 'TRAY'. data lr_tray type ref to cl_wd_tray. lr_tray ?= lr_element. set_visible lr_tray ls_metadata. set_enabled lr_tray ls_metadata. elseif lr_element->_definition_name = 'VIEW_CONTAINER_UIELEMENT'. data lr_vcuie type ref to cl_wd_view_container_uielement. lr_vcuie ?= lr_element. set_visible lr_vcuie ls_metadata. set_enabled lr_vcuie ls_metadata. elseif lr_element->_definition_name = 'CHECKBOX'. data lr_checkbox type ref to cl_wd_checkbox. lr_checkbox ?= lr_element. set_all lr_checkbox ls_metadata. elseif lr_element->_definition_name = 'LINK_TO_ACTION'. data lr_lnk_a type ref to cl_wd_link_to_action. lr_lnk_a ?= lr_element. set_visible lr_lnk_a ls_metadata. set_enabled lr_lnk_a ls_metadata. elseif lr_element->_definition_name = 'IMAGE'. data lr_image type ref to cl_wd_image. lr_image ?= lr_element. set_visible lr_image ls_metadata. set_enabled lr_image ls_metadata. elseif lr_element->_definition_name = 'GROUP'. data lr_group type ref to cl_wd_group. lr_group ?= lr_element. set_visible lr_group ls_metadata. set_enabled lr_group ls_metadata. elseif lr_element->_definition_name = 'TEXT_VIEW'. data lr_text_view type ref to cl_wd_text_view. lr_text_view ?= lr_element. set_visible lr_text_view ls_metadata. set_enabled lr_text_view ls_metadata. elseif lr_element->_definition_name = 'FORMATTED_TEXT_VIEW'. data lr_formatted_text_view type ref to cl_wd_formatted_text_view. lr_formatted_text_view ?= lr_element. set_visible lr_formatted_text_view ls_metadata. set_enabled lr_formatted_text_view ls_metadata. elseif lr_element->_definition_name = 'TABLE'. data lr_table type ref to cl_wd_table. lr_table ?= lr_element. set_visible lr_table ls_metadata. data lt_table_columns type cl_wd_abstr_table_column=>tt_abstr_table_column. lt_table_columns = lr_table->get_grouped_columns( ). data ls_column like line of lt_table_columns. loop at lt_table_columns into ls_column. data ls_col_meta like line of it_metadata. read table it_metadata into ls_col_meta with key field = ls_column->id. check sy-subrc eq 0. data lr_table_column type ref to cl_wd_table_column. lr_table_column ?= ls_column. data lr_table_cell_editor type ref to if_wd_table_cell_editor. lr_table_cell_editor = lr_table_column->get_table_cell_editor( ). set_visible ls_column ls_col_meta. lr_element ?= lr_table_cell_editor. try. case lr_element->_definition_name. when 'INPUT_FIELD'. lr_input_field ?= lr_table_cell_editor. set_all lr_input_field ls_col_meta. when 'TEXT_EDIT'. lr_text_edit ?= lr_table_cell_editor. set_all lr_text_edit ls_col_meta. when 'CHECKBOX'. lr_checkbox ?= lr_table_cell_editor. set_all lr_checkbox ls_col_meta. endcase. catch cx_root. endtry. endloop. endif. endloop. endmethod. ENDCLASS. ",7421,False,1461.703592428515,median "//// DO NOT EDIT THIS FILE. IT WAS GENERATED. Manual changes to this file will be lost when it is generated again. Edit the files in the src/main/asciidoc/ directory instead. //// :jdkversion: 1.8 :github-tag: master :github-repo: spring-cloud/spring-cloud-stream-binder-rabbit :github-raw: https://raw.githubusercontent.com/{github-repo}/{github-tag} :github-code: https://github.com/{github-repo}/tree/{github-tag} image::https://circleci.com/gh/spring-cloud/spring-cloud-stream-binder-rabbit.svg?style=svg[""CircleCI"", link=""https://circleci.com/gh/spring-cloud/spring-cloud-stream-binder-rabbit""] image::https://codecov.io/gh/spring-cloud/spring-cloud-stream-binder-rabbit/branch/{github-tag}/graph/badge.svg[""codecov"", link=""https://codecov.io/gh/spring-cloud/spring-cloud-stream-binder-rabbit""] image::https://badges.gitter.im/spring-cloud/spring-cloud-stream-binder-rabbit.svg[Gitter, link=""https://gitter.im/spring-cloud/spring-cloud-stream-binder-rabbit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge""] // ====================================================================================== //= Overview [partintro] -- This guide describes the RabbitMQ implementation of the Spring Cloud Stream Binder. It contains information about its design, usage and configuration options, as well as information on how the Stream Cloud Stream concepts map into RabbitMQ specific constructs. -- == Usage To use the RabbitMQ binder, you can add it to your Spring Cloud Stream application, by using the following Maven coordinates: [source,xml] ---- org.springframework.cloud spring-cloud-stream-binder-rabbit ---- Alternatively, you can use the Spring Cloud Stream RabbitMQ Starter, as follows: [source,xml] ---- org.springframework.cloud spring-cloud-starter-stream-rabbit ---- == RabbitMQ Binder Overview The following simplified diagram shows how the RabbitMQ binder operates: .RabbitMQ Binder image::{github-raw}/docs/src/main/asciidoc/images/rabbit-binder.png[width=300,scaledwidth=""50%""] By default, the RabbitMQ Binder implementation maps each destination to a `TopicExchange`. For each consumer group, a `Queue` is bound to that `TopicExchange`. Each consumer instance has a corresponding RabbitMQ `Consumer` instance for its group's `Queue`. For partitioned producers and consumers, the queues are suffixed with the partition index and use the partition index as the routing key. For anonymous consumers (those with no `group` property), an auto-delete queue (with a randomized unique name) is used. By using the optional `autoBindDlq` option, you can configure the binder to create and configure dead-letter queues (DLQs) (and a dead-letter exchange `DLX`, as well as routing infrastructure). By default, the dead letter queue has the name of the destination, appended with `.dlq`. If retry is enabled (`maxAttempts > 1`), failed messages are delivered to the DLQ after retries are exhausted. If retry is disabled (`maxAttempts = 1`), you should set `requeueRejected` to `false` (the default) so that failed messages are routed to the DLQ, instead of being re-queued. In addition, `republishToDlq` causes the binder to publish a failed message to the DLQ (instead of rejecting it). This feature lets additional information (such as the stack trace in the `x-exception-stacktrace` header) be added to the message in headers. See the <> for information about truncated stack traces. This option does not need retry enabled. You can republish a failed message after just one attempt. Starting with version 1.2, you can configure the delivery mode of republished messages. See the <>. If the stream listener throws an `ImmediateAcknowledgeAmqpException`, the DLQ is bypassed and the message simply discarded. Starting with version 2.1, this is true regardless of the setting of `republishToDlq`; previously it was only the case when `republishToDlq` was `false`. IMPORTANT: Setting `requeueRejected` to `true` (with `republishToDlq=false` ) causes the message to be re-queued and redelivered continually, which is likely not what you want unless the reason for the failure is transient. In general, you should enable retry within the binder by setting `maxAttempts` to greater than one or by setting `republishToDlq` to `true`. Starting with version 3.1.2, if the consumer is marked as `transacted`, publishing to the DLQ will participate in the transaction. This allows the transaction to roll back if the publishing fails for some reason (for example, if the user is not authorized to publish to the dead letter exchange). In addition, if the connection factory is configured for publisher confirms or returns, the publication to the DLQ will wait for the confirmation and check for a returned message. If a negative acknowledgment or returned message is received, the binder will throw an `AmqpRejectAndDontRequeueException`, allowing the broker to take care of publishing to the DLQ as if the `republishToDlq` property is `false`. See <> for more information about these properties. The framework does not provide any standard mechanism to consume dead-letter messages (or to re-route them back to the primary queue). Some options are described in <>. NOTE: When multiple RabbitMQ binders are used in a Spring Cloud Stream application, it is important to disable 'RabbitAutoConfiguration' to avoid the same configuration from `RabbitAutoConfiguration` being applied to the two binders. You can exclude the class by using the `@SpringBootApplication` annotation. Starting with version 2.0, the `RabbitMessageChannelBinder` sets the `RabbitTemplate.userPublisherConnection` property to `true` so that the non-transactional producers avoid deadlocks on consumers, which can happen if cached connections are blocked because of a https://www.rabbitmq.com/memory.html[memory alarm] on the broker. NOTE: Currently, a `multiplex` consumer (a single consumer listening to multiple queues) is only supported for message-driven consumers; polled consumers can only retrieve messages from a single queue. == Configuration Options This section contains settings specific to the RabbitMQ Binder and bound channels. For general binding configuration options and properties, see the https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/current/reference/html/spring-cloud-stream.html#_configuration_options[Spring Cloud Stream core documentation]. [[rabbit-binder-properties]] === RabbitMQ Binder Properties By default, the RabbitMQ binder uses Spring Boot's `ConnectionFactory`. Conseuqently, it supports all Spring Boot configuration options for RabbitMQ. (For reference, see the https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties[Spring Boot documentation]). RabbitMQ configuration options use the `spring.rabbitmq` prefix. In addition to Spring Boot options, the RabbitMQ binder supports the following properties: spring.cloud.stream.rabbit.binder.adminAddresses:: A comma-separated list of RabbitMQ management plugin URLs. Only used when `nodes` contains more than one entry. Each entry in this list must have a corresponding entry in `spring.rabbitmq.addresses`. Only needed if you use a RabbitMQ cluster and wish to consume from the node that hosts the queue. See https://docs.spring.io/spring-amqp/reference/html/#queue-affinity[Queue Affinity and the LocalizedQueueConnectionFactory] for more information. + Default: empty. spring.cloud.stream.rabbit.binder.nodes:: A comma-separated list of RabbitMQ node names. When more than one entry, used to locate the server address where a queue is located. Each entry in this list must have a corresponding entry in `spring.rabbitmq.addresses`. Only needed if you use a RabbitMQ cluster and wish to consume from the node that hosts the queue. See https://docs.spring.io/spring-amqp/reference/html/_reference.html#queue-affinity[Queue Affinity and the LocalizedQueueConnectionFactory] for more information. + Default: empty. spring.cloud.stream.rabbit.binder.compressionLevel:: The compression level for compressed bindings. See `java.util.zip.Deflater`. + Default: `1` (BEST_LEVEL). spring.cloud.stream.binder.connection-name-prefix:: A connection name prefix used to name the connection(s) created by this binder. The name is this prefix followed by `#n`, where `n` increments each time a new connection is opened. + Default: none (Spring AMQP default). === RabbitMQ Consumer Properties The following properties are available for Rabbit consumers only and must be prefixed with `spring.cloud.stream.rabbit.bindings..consumer.`. However if the same set of properties needs to be applied to most bindings, to avoid repetition, Spring Cloud Stream supports setting values for all channels, in the format of `spring.cloud.stream.rabbit.default.=`. Also, keep in mind that binding specific property will override its equivalent in the default. acknowledgeMode:: The acknowledge mode. + Default: `AUTO`. anonymousGroupPrefix:: When the binding has no `group` property, an anonymous, auto-delete queue is bound to the destination exchange. The default naming stragegy for such queues results in a queue named `anonymous.`. Set this property to change the prefix to something other than the default. + Default: `anonymous.`. autoBindDlq:: Whether to automatically declare the DLQ and bind it to the binder DLX. + Default: `false`. bindingRoutingKey:: The routing key with which to bind the queue to the exchange (if `bindQueue` is `true`). Can be multiple keys - see `bindingRoutingKeyDelimiter`. For partitioned destinations, `-` is appended to each key. + Default: `#`. bindingRoutingKeyDelimiter:: When this is not null, 'bindingRoutingKey' is considered to be a list of keys delimited by this value; often a comma is used. + Default: `null`. bindQueue:: Whether to declare the queue and bind it to the destination exchange. Set it to `false` if you have set up your own infrastructure and have previously created and bound the queue. + Default: `true`. consumerTagPrefix:: Used to create the consumer tag(s); will be appended by `#n` where `n` increments for each consumer created. Example: `${spring.application.name}-${spring.cloud.stream.bindings.input.group}-${spring.cloud.stream.instance-index}`. + Default: none - the broker will generate random consumer tags. containerType:: Select the type of listener container to be used. See https://docs.spring.io/spring-amqp/reference/html/_reference.html#choose-container[Choosing a Container] in the Spring AMQP documentation for more information. + Default: `simple` deadLetterQueueName:: The name of the DLQ + Default: `prefix+destination.dlq` deadLetterExchange:: A DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: 'prefix+DLX' deadLetterExchangeType:: The type of the DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: 'direct' deadLetterRoutingKey:: A dead letter routing key to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: `destination` declareDlx:: Whether to declare the dead letter exchange for the destination. Relevant only if `autoBindDlq` is `true`. Set to `false` if you have a pre-configured DLX. + Default: `true`. declareExchange:: Whether to declare the exchange for the destination. + Default: `true`. delayedExchange:: Whether to declare the exchange as a `Delayed Message Exchange`. Requires the delayed message exchange plugin on the broker. The `x-delayed-type` argument is set to the `exchangeType`. + Default: `false`. dlqBindingArguments:: Arguments applied when binding the dlq to the dead letter exchange; used with `headers` `deadLetterExchangeType` to specify headers to match on. For example `...dlqBindingArguments.x-match=any`, `...dlqBindingArguments.someHeader=someValue`. + Default: empty dlqDeadLetterExchange:: If a DLQ is declared, a DLX to assign to that queue. + Default: `none` dlqDeadLetterRoutingKey:: If a DLQ is declared, a dead letter routing key to assign to that queue. + Default: `none` dlqExpires:: How long before an unused dead letter queue is deleted (in milliseconds). + Default: `no expiration` dlqLazy:: Declare the dead letter queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. + Default: `false`. dlqMaxLength:: Maximum number of messages in the dead letter queue. + Default: `no limit` dlqMaxLengthBytes:: Maximum number of total bytes in the dead letter queue from all messages. + Default: `no limit` dlqMaxPriority:: Maximum priority of messages in the dead letter queue (0-255). + Default: `none` dlqOverflowBehavior:: Action to take when `dlqMaxLength` or `dlqMaxLengthBytes` is exceeded; currently `drop-head` or `reject-publish` but refer to the RabbitMQ documentation. + Default: `none` dlqQuorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. + Default: none - broker default will apply. dlqQuorum.enabled:: When true, create a quorum dead letter queue instead of a classic queue. + Default: false dlqQuorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. + Default: none - broker default will apply. dlqSingleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. + Default: `false` dlqTtl:: Default time to live to apply to the dead letter queue when declared (in milliseconds). + Default: `no limit` durableSubscription:: Whether the subscription should be durable. Only effective if `group` is also set. + Default: `true`. exchangeAutoDelete:: If `declareExchange` is true, whether the exchange should be auto-deleted (that is, removed after the last queue is removed). + Default: `true`. exchangeDurable:: If `declareExchange` is true, whether the exchange should be durable (that is, it survives broker restart). + Default: `true`. exchangeType:: The exchange type: `direct`, `fanout`, `headers` or `topic` for non-partitioned destinations and `direct`, headers or `topic` for partitioned destinations. + Default: `topic`. exclusive:: Whether to create an exclusive consumer. Concurrency should be 1 when this is `true`. Often used when strict ordering is required but enabling a hot standby instance to take over after a failure. See `recoveryInterval`, which controls how often a standby instance attempts to consume. Consider using `singleActiveConsumer` instead when using RabbitMQ 3.8 or later. + Default: `false`. expires:: How long before an unused queue is deleted (in milliseconds). + Default: `no expiration` failedDeclarationRetryInterval:: The interval (in milliseconds) between attempts to consume from a queue if it is missing. + Default: 5000 [[spring-cloud-stream-rabbit-frame-max-headroom]] frameMaxHeadroom:: The number of bytes to reserve for other headers when adding the stack trace to a DLQ message header. All headers must fit within the `frame_max` size configured on the broker. Stack traces can be large; if the size plus this property exceeds `frame_max` then the stack trace will be truncated. A WARN log will be written; consider increasing the `frame_max` or reducing the stack trace by catching the exception and throwing one with a smaller stack trace. + Default: 20000 headerPatterns:: Patterns for headers to be mapped from inbound messages. + Default: `['*']` (all headers). lazy:: Declare the queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. + Default: `false`. maxConcurrency:: The maximum number of consumers. Not supported when the `containerType` is `direct`. + Default: `1`. maxLength:: The maximum number of messages in the queue. + Default: `no limit` maxLengthBytes:: The maximum number of total bytes in the queue from all messages. + Default: `no limit` maxPriority:: The maximum priority of messages in the queue (0-255). + Default: `none` missingQueuesFatal:: When the queue cannot be found, whether to treat the condition as fatal and stop the listener container. Defaults to `false` so that the container keeps trying to consume from the queue -- for example, when using a cluster and the node hosting a non-HA queue is down. + Default: `false` overflowBehavior:: Action to take when `maxLength` or `maxLengthBytes` is exceeded; currently `drop-head` or `reject-publish` but refer to the RabbitMQ documentation. + Default: `none` prefetch:: Prefetch count. + Default: `1`. prefix:: A prefix to be added to the name of the `destination` and queues. + Default: """". queueBindingArguments:: Arguments applied when binding the queue to the exchange; used with `headers` `exchangeType` to specify headers to match on. For example `...queueBindingArguments.x-match=any`, `...queueBindingArguments.someHeader=someValue`. + Default: empty queueDeclarationRetries:: The number of times to retry consuming from a queue if it is missing. Relevant only when `missingQueuesFatal` is `true`. Otherwise, the container keeps retrying indefinitely. Not supported when the `containerType` is `direct`. + Default: `3` queueNameGroupOnly:: When true, consume from a queue with a name equal to the `group`. Otherwise the queue name is `destination.group`. This is useful, for example, when using Spring Cloud Stream to consume from an existing RabbitMQ queue. + Default: false. quorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. + Default: none - broker default will apply. quorum.enabled:: When true, create a quorum queue instead of a classic queue. + Default: false quorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. + Default: none - broker default will apply. recoveryInterval:: The interval between connection recovery attempts, in milliseconds. + Default: `5000`. requeueRejected:: Whether delivery failures should be re-queued when retry is disabled or `republishToDlq` is `false`. + Default: `false`. [[spring-cloud-stream-rabbit-republish-delivery-mode]] republishDeliveryMode:: When `republishToDlq` is `true`, specifies the delivery mode of the republished message. + Default: `DeliveryMode.PERSISTENT` republishToDlq:: By default, messages that fail after retries are exhausted are rejected. If a dead-letter queue (DLQ) is configured, RabbitMQ routes the failed message (unchanged) to the DLQ. If set to `true`, the binder republishs failed messages to the DLQ with additional headers, including the exception message and stack trace from the cause of the final failure. Also see the <>. + Default: `true` singleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. + Default: `false` transacted:: Whether to use transacted channels. + Default: `false`. ttl:: Default time to live to apply to the queue when declared (in milliseconds). + Default: `no limit` txSize:: The number of deliveries between acks. Not supported when the `containerType` is `direct`. + Default: `1`. === Advanced Listener Container Configuration To set listener container properties that are not exposed as binder or binding properties, add a single bean of type `ListenerContainerCustomizer` to the application context. The binder and binding properties will be set and then the customizer will be called. The customizer (`configure()` method) is provided with the queue name as well as the consumer group as arguments. === Advanced Queue/Exchange/Binding Configuration From time to time, the RabbitMQ team add new features that are enabled by setting some argument when declaring, for example, a queue. Generally, such features are enabled in the binder by adding appropriate properties, but this may not be immediately available in a current version. Starting with version 3.0.1, you can now add `DeclarableCustomizer` bean(s) to the application context to modify a `Declarable` (`Queue`, `Exchange` or `Binding`) just before the declaration is performed. This allows you to add arguments that are not currently directly supported by the binder. [[rabbit-receiving-batch]] === Receiving Batched Messages With the RabbitMQ binder, there are two types of batches handled by consumer bindings: ==== Batches Created by Producers Normally, if a producer binding has `batch-enabled=true` (see <>), or a message is created by a `BatchingRabbitTemplate`, elements of the batch are returned as individual calls to the listener method. Starting with version 3.0, any such batch can be presented as a `List` to the listener method if `spring.cloud.stream.bindings..consumer.batch-mode` is set to `true`. ==== Consumer-side Batching Starting with version 3.1, the consumer can be configured to assemble multiple inbound messages into a batch which is presented to the application as a `List` of converted payloads. The following simple application demonstrates how to use this technique: ==== [source, properties] ---- spring.cloud.stream.bindings.input-in-0.group=someGroup spring.cloud.stream.bindings.input-in-0.consumer.batch-mode=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.enable-batching=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.batch-size=10 spring.cloud.stream.rabbit.bindings.input-in-0.consumer.receive-timeout=200 ---- ==== ==== [source, java] ---- @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean Consumer> input() { return list -> { System.out.println(""Received "" + list.size()); list.forEach(thing -> { System.out.println(thing); // ... }); }; } @Bean public ApplicationRunner runner(RabbitTemplate template) { return args -> { template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value1\\""}""); template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value2\\""}""); }; } public static class Thing { private String field; public Thing() { } public Thing(String field) { this.field = field; } public String getField() { return this.field; } public void setField(String field) { this.field = field; } @Override public String toString() { return ""Thing [field="" + this.field + ""]""; } } } ---- ==== ==== [source] ---- Received 2 Thing [field=value1] Thing [field=value2] ---- ==== The number of messages in a batch is specified by the `batch-size` and `receive-timeout` properties; if the `receive-timeout` elapses with no new messages, a ""short"" batch is delivered. IMPORTANT: Consumer-side batching is only supported with `container-type=simple` (the default). If you wish to examine headers of consumer-side batched messages, you should consume `Message>`; the headers are a `List>` in a header `AmqpInboundChannelAdapter.CONSOLIDATED_HEADERS`, with the headers for each payload element in the corresponding index. Again, here is a simple example: ==== [source, java] ---- @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean Consumer>> input() { return msg -> { List things = msg.getPayload(); System.out.println(""Received "" + things.size()); @SuppressWarnings(""unchecked"") List> headers = (List>) msg.getHeaders().get(AmqpInboundChannelAdapter.CONSOLIDATED_HEADERS); for (int i = 0; i < things.size(); i++) { System.out.println(things.get(i) + "" myHeader="" + headers.get(i).get(""myHeader"")); // ... } }; } @Bean public ApplicationRunner runner(RabbitTemplate template) { return args -> { template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value1\\""}"", msg -> { msg.getMessageProperties().setHeader(""myHeader"", ""headerValue1""); return msg; }); template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value2\\""}"", msg -> { msg.getMessageProperties().setHeader(""myHeader"", ""headerValue2""); return msg; }); }; } public static class Thing { private String field; public Thing() { } public Thing(String field) { this.field = field; } public String getfield() { return this.field; } public void setfield(String field) { this.field = field; } @Override public String toString() { return ""Thing [field="" + this.field + ""]""; } } } ---- ==== ==== [source] ---- Received 2 Thing [field=value1] myHeader=headerValue1 Thing [field=value2] myHeader=headerValue2 ---- ==== [[rabbit-prod-props]] === Rabbit Producer Properties The following properties are available for Rabbit producers only and must be prefixed with `spring.cloud.stream.rabbit.bindings..producer.`. However if the same set of properties needs to be applied to most bindings, to avoid repetition, Spring Cloud Stream supports setting values for all channels, in the format of `spring.cloud.stream.rabbit.default.=`. Also, keep in mind that binding specific property will override its equivalent in the default. autoBindDlq:: Whether to automatically declare the DLQ and bind it to the binder DLX. + Default: `false`. batchingEnabled:: Whether to enable message batching by producers. Messages are batched into one message according to the following properties (described in the next three entries in this list): 'batchSize', `batchBufferLimit`, and `batchTimeout`. See https://docs.spring.io/spring-amqp//reference/html/_reference.html#template-batching[Batching] for more information. Also see <>. + Default: `false`. batchSize:: The number of messages to buffer when batching is enabled. + Default: `100`. batchBufferLimit:: The maximum buffer size when batching is enabled. + Default: `10000`. batchTimeout:: The batch timeout when batching is enabled. + Default: `5000`. bindingRoutingKey:: The routing key with which to bind the queue to the exchange (if `bindQueue` is `true`). Can be multiple keys - see `bindingRoutingKeyDelimiter`. For partitioned destinations, `-n` is appended to each key. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `#`. bindingRoutingKeyDelimiter:: When this is not null, 'bindingRoutingKey' is considered to be a list of keys delimited by this value; often a comma is used. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `null`. bindQueue:: Whether to declare the queue and bind it to the destination exchange. Set it to `false` if you have set up your own infrastructure and have previously created and bound the queue. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `true`. compress:: Whether data should be compressed when sent. + Default: `false`. confirmAckChannel:: When `errorChannelEnabled` is true, a channel to which to send positive delivery acknowledgments (aka publisher confirms). If the channel does not exist, a `DirectChannel` is registered with this name. The connection factory must be configured to enable publisher confirms. Mutually exclusive with `useConfirmHeader`. + Default: `nullChannel` (acks are discarded). deadLetterQueueName:: The name of the DLQ Only applies if `requiredGroups` are provided and then only to those groups. + Default: `prefix+destination.dlq` deadLetterExchange:: A DLX to assign to the queue. Relevant only when `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: 'prefix+DLX' deadLetterExchangeType:: The type of the DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: 'direct' deadLetterRoutingKey:: A dead letter routing key to assign to the queue. Relevant only when `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `destination` declareDlx:: Whether to declare the dead letter exchange for the destination. Relevant only if `autoBindDlq` is `true`. Set to `false` if you have a pre-configured DLX. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `true`. declareExchange:: Whether to declare the exchange for the destination. + Default: `true`. delayExpression:: A SpEL expression to evaluate the delay to apply to the message (`x-delay` header). It has no effect if the exchange is not a delayed message exchange. + Default: No `x-delay` header is set. delayedExchange:: Whether to declare the exchange as a `Delayed Message Exchange`. Requires the delayed message exchange plugin on the broker. The `x-delayed-type` argument is set to the `exchangeType`. + Default: `false`. deliveryMode:: The delivery mode. + Default: `PERSISTENT`. dlqBindingArguments:: Arguments applied when binding the dlq to the dead letter exchange; used with `headers` `deadLetterExchangeType` to specify headers to match on. For example `...dlqBindingArguments.x-match=any`, `...dlqBindingArguments.someHeader=someValue`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: empty dlqDeadLetterExchange:: When a DLQ is declared, a DLX to assign to that queue. Applies only if `requiredGroups` are provided and then only to those groups. + Default: `none` dlqDeadLetterRoutingKey:: When a DLQ is declared, a dead letter routing key to assign to that queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `none` dlqExpires:: How long (in milliseconds) before an unused dead letter queue is deleted. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no expiration` dlqLazy:: Declare the dead letter queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. Applies only when `requiredGroups` are provided and then only to those groups. + dlqMaxLength:: Maximum number of messages in the dead letter queue. Applies only if `requiredGroups` are provided and then only to those groups. + Default: `no limit` dlqMaxLengthBytes:: Maximum number of total bytes in the dead letter queue from all messages. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` dlqMaxPriority:: Maximum priority of messages in the dead letter queue (0-255) Applies only when `requiredGroups` are provided and then only to those groups. + Default: `none` dlqQuorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. dlqQuorum.enabled:: When true, create a quorum dead letter queue instead of a classic queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false dlqQuorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. dlqSingleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false` dlqTtl:: Default time (in milliseconds) to live to apply to the dead letter queue when declared. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` exchangeAutoDelete:: If `declareExchange` is `true`, whether the exchange should be auto-delete (it is removed after the last queue is removed). + Default: `true`. exchangeDurable:: If `declareExchange` is `true`, whether the exchange should be durable (survives broker restart). + Default: `true`. exchangeType:: The exchange type: `direct`, `fanout`, `headers` or `topic` for non-partitioned destinations and `direct`, `headers` or `topic` for partitioned destinations. + Default: `topic`. expires:: How long (in milliseconds) before an unused queue is deleted. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no expiration` headerPatterns:: Patterns for headers to be mapped to outbound messages. + Default: `['*']` (all headers). lazy:: Declare the queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false`. maxLength:: Maximum number of messages in the queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` maxLengthBytes:: Maximum number of total bytes in the queue from all messages. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `no limit` maxPriority:: Maximum priority of messages in the queue (0-255). Only applies if `requiredGroups` are provided and then only to those groups. + Default: `none` prefix:: A prefix to be added to the name of the `destination` exchange. + Default: """". queueBindingArguments:: Arguments applied when binding the queue to the exchange; used with `headers` `exchangeType` to specify headers to match on. For example `...queueBindingArguments.x-match=any`, `...queueBindingArguments.someHeader=someValue`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: empty queueNameGroupOnly:: When `true`, consume from a queue with a name equal to the `group`. Otherwise the queue name is `destination.group`. This is useful, for example, when using Spring Cloud Stream to consume from an existing RabbitMQ queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false. quorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. quorum.enabled:: When true, create a quorum queue instead of a classic queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false quorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. routingKeyExpression:: A SpEL expression to determine the routing key to use when publishing messages. For a fixed routing key, use `routingKey`. + Default: `destination` or `destination-` for partitioned destinations. routingKey:: A string defining a fixed routing key to use when publishing messages. + Default: see `routingKeyExpression` singleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false` transacted:: Whether to use transacted channels. + Default: `false`. ttl:: Default time (in milliseconds) to live to apply to the queue when declared. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` useConfirmHeader:: See <>. Mutually exclusive with `confirmAckChannel`. + NOTE: In the case of RabbitMQ, content type headers can be set by external applications. Spring Cloud Stream supports them as part of an extended internal protocol used for any type of transport -- including transports, such as Kafka (prior to 0.11), that do not natively support headers. [[publisher-confirms]] === Publisher Confirms There are two mechanisms to get the result of publishing a message; in each case, the connection factory must have `publisherConfirmType` set `ConfirmType.CORRELATED`. The ""legacy"" mechanism is to set the `confirmAckChannel` to the bean name of a message channel from which you can retrieve the confirmations asynchronously; negative acks are sent to the error channel (if enabled) - see <>. The preferred mechanism, added in version 3.1 is to use a correlation data header and wait for the result via its `Future` property. This is particularly useful with a batch listener because you can send multiple messages before waiting for the result. To use this technique, set the `useConfirmHeader` property to true The following simple application is an example of using this technique: ==== [source, properties] ---- spring.cloud.stream.bindings.input-in-0.group=someGroup spring.cloud.stream.bindings.input-in-0.consumer.batch-mode=true spring.cloud.stream.source=output spring.cloud.stream.bindings.output-out-0.producer.error-channel-enabled=true spring.cloud.stream.rabbit.bindings.output-out-0.producer.useConfirmHeader=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.auto-bind-dlq=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.batch-size=10 spring.rabbitmq.publisher-confirm-type=correlated spring.rabbitmq.publisher-returns=true ---- ==== ==== [source, java] ---- @SpringBootApplication public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired private StreamBridge bridge; @Bean Consumer> input() { return list -> { List results = new ArrayList<>(); list.forEach(str -> { log.info(""Received: "" + str); MyCorrelationData corr = new MyCorrelationData(UUID.randomUUID().toString(), str); results.add(corr); this.bridge.send(""output-out-0"", MessageBuilder.withPayload(str.toUpperCase()) .setHeader(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION, corr) .build()); }); results.forEach(correlation -> { try { Confirm confirm = correlation.getFuture().get(10, TimeUnit.SECONDS); log.info(confirm + "" for "" + correlation.getPayload()); if (correlation.getReturnedMessage() != null) { log.error(""Message for "" + correlation.getPayload() + "" was returned ""); // try to re-publish, send a DLQ, etc } } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } catch (ExecutionException | TimeoutException e) { e.printStackTrace(); } }); }; } @Bean public ApplicationRunner runner(BatchingRabbitTemplate template) { return args -> IntStream.range(0, 10).forEach(i -> template.convertAndSend(""input-in-0"", ""input-in-0.rbgh303"", ""foo"" + i)); } @Bean public BatchingRabbitTemplate template(CachingConnectionFactory cf, TaskScheduler taskScheduler) { BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(10, 1000000, 1000); return new BatchingRabbitTemplate(cf, batchingStrategy, taskScheduler); } } class MyCorrelationData extends CorrelationData { private final String payload; MyCorrelationData(String id, String payload) { super(id); this.payload = payload; } public String getPayload() { return this.payload; } } ---- ==== As you can see, we send each message and then await for the publication results. If the messages can't be routed, then correlation data is populated with the returned message before the future is completed. IMPORTANT: The correlation data must be provided with a unique `id` so that the framework can perform the correlation. You cannot set both `useConfirmHeader` and `confirmAckChannel` but you can still receive returned messages in the error channel when `useConfirmHeader` is true, but using the correlation header is more convenient. == Using Existing Queues/Exchanges By default, the binder will automatically provision a topic exchange with the name being derived from the value of the destination binding property ``. The destination defaults to the binding name, if not provided. When binding a consumer, a queue will automatically be provisioned with the name `.` (if a `group` binding property is specified), or an anonymous, auto-delete queue when there is no `group`. The queue will be bound to the exchange with the ""match-all"" wildcard routing key (`#`) for a non-partitioned binding or `-` for a partitioned binding. The prefix is an empty `String` by default. If an output binding is specified with `requiredGroups`, a queue/binding will be provisioned for each group. There are a number of rabbit-specific binding properties that allow you to modify this default behavior. If you have an existing exchange/queue that you wish to use, you can completely disable automatic provisioning as follows, assuming the exchange is named `myExchange` and the queue is named `myQueue`: * `spring.cloud.stream.bindings..destination=myExhange` * `spring.cloud.stream.bindings..group=myQueue` * `spring.cloud.stream.rabbit.bindings..consumer.bindQueue=false` * `spring.cloud.stream.rabbit.bindings..consumer.declareExchange=false` * `spring.cloud.stream.rabbit.bindings..consumer.queueNameGroupOnly=true` If you want the binder to provision the queue/exchange, but you want to do it using something other than the defaults discussed here, use the following properties. Refer to the property documentation above for more information. * `spring.cloud.stream.rabbit.bindings..consumer.bindingRoutingKey=myRoutingKey` * `spring.cloud.stream.rabbit.bindings..consumer.exchangeType=` * `spring.cloud.stream.rabbit.bindings..producer.routingKeyExpression='myRoutingKey'` There are similar properties used when declaring a dead-letter exchange/queue, when `autoBindDlq` is `true`. == Retry With the RabbitMQ Binder When retry is enabled within the binder, the listener container thread is suspended for any back off periods that are configured. This might be important when strict ordering is required with a single consumer. However, for other use cases, it prevents other messages from being processed on that thread. An alternative to using binder retry is to set up dead lettering with time to live on the dead-letter queue (DLQ) as well as dead-letter configuration on the DLQ itself. See ""`<>`"" for more information about the properties discussed here. You can use the following example configuration to enable this feature: * Set `autoBindDlq` to `true`. The binder create a DLQ. Optionally, you can specify a name in `deadLetterQueueName`. * Set `dlqTtl` to the back off time you want to wait between redeliveries. * Set the `dlqDeadLetterExchange` to the default exchange. Expired messages from the DLQ are routed to the original queue, because the default `deadLetterRoutingKey` is the queue name (`destination.group`). Setting to the default exchange is achieved by setting the property with no value, as shown in the next example. To force a message to be dead-lettered, either throw an `AmqpRejectAndDontRequeueException` or set `requeueRejected` to `false` (the default) and throw any exception. The loop continue without end, which is fine for transient problems, but you may want to give up after some number of attempts. Fortunately, RabbitMQ provides the `x-death` header, which lets you determine how many cycles have occurred. To acknowledge a message after giving up, throw an `ImmediateAcknowledgeAmqpException`. === Putting it All Together The following configuration creates an exchange `myDestination` with queue `myDestination.consumerGroup` bound to a topic exchange with a wildcard routing key `#`: [source] --- spring.cloud.stream.bindings.input.destination=myDestination spring.cloud.stream.bindings.input.group=consumerGroup #disable binder retries spring.cloud.stream.bindings.input.consumer.max-attempts=1 #dlx/dlq setup spring.cloud.stream.rabbit.bindings.input.consumer.auto-bind-dlq=true spring.cloud.stream.rabbit.bindings.input.consumer.dlq-ttl=5000 spring.cloud.stream.rabbit.bindings.input.consumer.dlq-dead-letter-exchange= --- This configuration creates a DLQ bound to a direct exchange (`DLX`) with a routing key of `myDestination.consumerGroup`. When messages are rejected, they are routed to the DLQ. After 5 seconds, the message expires and is routed to the original queue by using the queue name as the routing key, as shown in the following example: .Spring Boot application [source, java] ---- @SpringBootApplication @EnableBinding(Sink.class) public class XDeathApplication { public static void main(String[] args) { SpringApplication.run(XDeathApplication.class, args); } @StreamListener(Sink.INPUT) public void listen(String in, @Header(name = ""x-death"", required = false) Map death) { if (death != null && death.get(""count"").equals(3L)) { // giving up - don't send to DLX throw new ImmediateAcknowledgeAmqpException(""Failed after 4 attempts""); } throw new AmqpRejectAndDontRequeueException(""failed""); } } ---- Notice that the count property in the `x-death` header is a `Long`. [[rabbit-error-channels]] == Error Channels Starting with version 1.3, the binder unconditionally sends exceptions to an error channel for each consumer destination and can also be configured to send async producer send failures to an error channel. See ""`<>`"" for more information. RabbitMQ has two types of send failures: * Returned messages, * Negatively acknowledged https://www.rabbitmq.com/confirms.html[Publisher Confirms]. The latter is rare. According to the RabbitMQ documentation ""[A nack] will only be delivered if an internal error occurs in the Erlang process responsible for a queue."". You can also get a negative acknowledgment if you publish to a bounded queue with `reject-publish` queue overflow behavior. As well as enabling producer error channels (as described in ""`<>`""), the RabbitMQ binder only sends messages to the channels if the connection factory is appropriately configured, as follows: * `ccf.setPublisherConfirms(true);` * `ccf.setPublisherReturns(true);` When using Spring Boot configuration for the connection factory, set the following properties: * `spring.rabbitmq.publisher-confirms` * `spring.rabbitmq.publisher-returns` The payload of the `ErrorMessage` for a returned message is a `ReturnedAmqpMessageException` with the following properties: * `failedMessage`: The spring-messaging `Message` that failed to be sent. * `amqpMessage`: The raw spring-amqp `Message`. * `replyCode`: An integer value indicating the reason for the failure (for example, 312 - No route). * `replyText`: A text value indicating the reason for the failure (for example, `NO_ROUTE`). * `exchange`: The exchange to which the message was published. * `routingKey`: The routing key used when the message was published. Also see <> for an alternative mechanism to receive returned messages. For negatively acknowledged confirmations, the payload is a `NackedAmqpMessageException` with the following properties: * `failedMessage`: The spring-messaging `Message` that failed to be sent. * `nackReason`: A reason (if available -- you may need to examine the broker logs for more information). There is no automatic handling of these exceptions (such as sending to a <>). You can consume these exceptions with your own Spring Integration flow. = Appendices [appendix] [[building]] == Building :jdkversion: 1.8 === Basic Compile and Test Pre-requisites: * To compile, JDK {jdkversion} installed. * To run tests, RabbitMQ server running on `localhost:5672` The build uses the Maven wrapper so you don't have to install a specific version of Maven. The main build command is ---- $ ./mvnw clean install ---- NOTE: There are scripts in `./ci-docker-compose` that use https://docs.docker.com/compose//[Docker Compose] to start/stop a local RabbitMQ server. You can also add '-DskipTests' if you like, to avoid running the tests. NOTE: You can also install Maven (>=3.3.3) yourself and run the `mvn` command in place of `./mvnw` in the examples below. If you do that you also might need to add `-P spring` if your local Maven settings do not contain repository declarations for spring pre-release artifacts. NOTE: Be aware that you might need to increase the amount of memory available to Maven by setting a `MAVEN_OPTS` environment variable with a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in the `.mvn` configuration, so if you find you have to do it to make a build succeed, please raise a ticket to get the settings added to source control. === Documentation There is a ""docs"" profile that will generate documentation. `./mvnw clean package -Pdocs -DskipTests` The reference documentation can then be found in `docs/target/contents/reference`. === Working with the code If you don't have an IDE preference we would recommend that you use https://www.springsource.com/developer/sts[Spring Tools Suite] or https://eclipse.org[Eclipse] when working with the code. We use the https://eclipse.org/m2e/[m2eclipe] eclipse plugin for maven support. Other IDEs and tools should also work without issue. ==== Importing into eclipse with m2eclipse We recommend the https://eclipse.org/m2e/[m2eclipe] eclipse plugin when working with eclipse. If you don't already have m2eclipse installed it is available from the ""eclipse marketplace"". Unfortunately m2e does not yet support Maven 3.3, so once the projects are imported into Eclipse you will also need to tell m2eclipse to use the `.settings.xml` file for the projects. If you do not do this you may see many different errors related to the POMs in the projects. Open your Eclipse preferences, expand the Maven preferences, and select User Settings. In the User Settings field click Browse and navigate to the Spring Cloud project you imported selecting the `.settings.xml` file in that project. Click Apply and then OK to save the preference changes. NOTE: Alternatively you can copy the repository settings from https://github.com/spring-cloud/spring-cloud-build/blob/master/.settings.xml[`.settings.xml`] into your own `~/.m2/settings.xml`. ==== Importing into eclipse without m2eclipse If you prefer not to use m2eclipse you can generate eclipse project metadata using the following command: [indent=0] ---- $ ./mvnw eclipse:eclipse ---- The generated eclipse projects can be imported by selecting `import existing projects` from the `file` menu. [[contributing]] == Contributing Spring Cloud is released under the non-restrictive Apache 2.0 license, and follows a very standard Github development process, using Github tracker for issues and merging pull requests into master. If you want to contribute even something trivial please do not hesitate, but follow the guidelines below. === Sign the Contributor License Agreement Before we accept a non-trivial patch or pull request we will need you to sign the https://support.springsource.com/spring_committer_signup[contributor's agreement]. Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests. === Code Conventions and Housekeeping None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge. * Use the Spring Framework code format conventions. If you use Eclipse you can import formatter settings using the `eclipse-code-formatter.xml` file from the https://github.com/spring-cloud/build/tree/master/eclipse-coding-conventions.xml[Spring Cloud Build] project. If using IntelliJ, you can use the https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter Plugin] to import the same file. * Make sure all new `.java` files to have a simple Javadoc class comment with at least an `@author` tag identifying you, and preferably at least a paragraph on what the class is for. * Add the ASF license header comment to all new `.java` files (copy from existing files in the project) * Add yourself as an `@author` to the .java files that you modify substantially (more than cosmetic changes). * Add some Javadocs and, if you change the namespace, some XSD doc elements. * A few unit tests would help a lot as well -- someone has to do it. * If no-one else is using your branch, please rebase it against the current master (or other target branch in the main project). * When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit message (where XXXX is the issue number). // ====================================================================================== ",12246,False,2256.2453856044654,median "/*************************************************************************/ /* gdscript.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* ""Software""), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include ""gdscript.h"" #include #include ""core/core_string_names.h"" #include ""core/engine.h"" #include ""core/global_constants.h"" #include ""core/io/file_access_encrypted.h"" #include ""core/os/file_access.h"" #include ""core/os/os.h"" #include ""core/project_settings.h"" #include ""gdscript_analyzer.h"" #include ""gdscript_cache.h"" #include ""gdscript_compiler.h"" #include ""gdscript_parser.h"" #include ""gdscript_warning.h"" /////////////////////////// GDScriptNativeClass::GDScriptNativeClass(const StringName &p_name) { name = p_name; } bool GDScriptNativeClass::_get(const StringName &p_name, Variant &r_ret) const { bool ok; int v = ClassDB::get_integer_constant(name, p_name, &ok); if (ok) { r_ret = v; return true; } else { return false; } } void GDScriptNativeClass::_bind_methods() { ClassDB::bind_method(D_METHOD(""new""), &GDScriptNativeClass::_new); } Variant GDScriptNativeClass::_new() { Object *o = instance(); ERR_FAIL_COND_V_MSG(!o, Variant(), ""Class type: '"" + String(name) + ""' is not instantiable.""); Reference *ref = Object::cast_to(o); if (ref) { return REF(ref); } else { return o; } } Object *GDScriptNativeClass::instance() { return ClassDB::instance(name); } void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error) { GDScript *base = p_script->_base; if (base != nullptr) { _super_implicit_constructor(base, p_instance, r_error); if (r_error.error != Callable::CallError::CALL_OK) { return; } } p_script->implicit_initializer->call(p_instance, nullptr, 0, r_error); } GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error) { /* STEP 1, CREATE */ GDScriptInstance *instance = memnew(GDScriptInstance); instance->base_ref = p_isref; instance->members.resize(member_indices.size()); instance->script = Ref(this); instance->owner = p_owner; instance->owner_id = p_owner->get_instance_id(); #ifdef DEBUG_ENABLED //needed for hot reloading for (Map::Element *E = member_indices.front(); E; E = E->next()) { instance->member_indices_cache[E->key()] = E->get().index; } #endif instance->owner->set_script_instance(instance); /* STEP 2, INITIALIZE AND CONSTRUCT */ { MutexLock lock(GDScriptLanguage::singleton->lock); instances.insert(instance->owner); } _super_implicit_constructor(this, instance, r_error); if (r_error.error != Callable::CallError::CALL_OK) { instance->script = Ref(); instance->owner->set_script_instance(nullptr); { MutexLock lock(GDScriptLanguage::singleton->lock); instances.erase(p_owner); } ERR_FAIL_V_MSG(nullptr, ""Error constructing a GDScriptInstance.""); } if (p_argcount < 0) { return instance; } if (initializer != nullptr) { initializer->call(instance, p_args, p_argcount, r_error); if (r_error.error != Callable::CallError::CALL_OK) { instance->script = Ref(); instance->owner->set_script_instance(nullptr); { MutexLock lock(GDScriptLanguage::singleton->lock); instances.erase(p_owner); } ERR_FAIL_V_MSG(nullptr, ""Error constructing a GDScriptInstance.""); } } //@TODO make thread safe return instance; } Variant GDScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) { /* STEP 1, CREATE */ if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); } r_error.error = Callable::CallError::CALL_OK; REF ref; Object *owner = nullptr; GDScript *_baseptr = this; while (_baseptr->_base) { _baseptr = _baseptr->_base; } ERR_FAIL_COND_V(_baseptr->native.is_null(), Variant()); if (_baseptr->native.ptr()) { owner = _baseptr->native->instance(); } else { owner = memnew(Reference); //by default, no base means use reference } ERR_FAIL_COND_V_MSG(!owner, Variant(), ""Can't inherit from a virtual class.""); Reference *r = Object::cast_to(owner); if (r) { ref = REF(r); } GDScriptInstance *instance = _create_instance(p_args, p_argcount, owner, r != nullptr, r_error); if (!instance) { if (ref.is_null()) { memdelete(owner); //no owner, sorry } return Variant(); } if (ref.is_valid()) { return ref; } else { return owner; } } bool GDScript::can_instance() const { #ifdef TOOLS_ENABLED return valid && (tool || ScriptServer::is_scripting_enabled()); #else return valid; #endif } Ref