Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[ABAP] JSON to ABAP with dereferencing

Recently I had to fetch an attachment from SuccessFactors. The API returns a huge JSON. Here only a few lines of that json.

{
    "d": {
        "__metadata": {
            "uri": "https://apihostname.successfactors.com:443/odata/v2/Attachment(1000)",
            "type": "SFOData.Attachment"
        },
        "attachmentId": "1000",
        "fileName": "Testdokument.pdf",
        "mimeType": "application/pdf",
        "moduleCategory": "HRIS_ATTACHMENT",
        "userId": "10000555",
        "fileExtension": "pdf",
        "fileContent": "JVBERi0xLjcKjp2jtMXW5/gKMiAwIG9iag0KWy9JQ0NCYXNlZCAzIDAgUl0NCmVuZG9iag0KMyAw\r\nIG9iag0KPDwNCi9GaWx0ZXIgL0ZsYXRlRGVjb2RlIA0KL0xlbmd0aCAyNTk2IA0KL04gMyANCj4+\r\nDQpzdHJlYW0NCnicnZZ3VFPZFofPvTe9UJIQipTQa2hSAkgNvUiRLioxCRBKwJAAIjZEVHBEUZGm\r\nCDIo4ICjQ5GxIoqFAVGx6wQZRNRxcBQblklkrRnfvHnvzZvfH/d+a5+9z91n733WugCQ/IMFwkxY\r\nCYAMoVgU4efFiI2LZ2AHAQzwAANsAOBws7NCFvhGApkCfNiMbJkT+Be9ug4g+fsq0z+MwQD/n5S5\r\nWSIxAFCYjOfy+NlcGRfJOD1XnCW3T8mYtjRNzjBKziJZgjJWk3PyLFt89pllDznzMoQ8GctzzuJl\r\n8OTcJ+ONORK+jJFgGRfnCPi5Mr4mY4N0SYZAxm/ksRl8TjYAKJLcLuZzU2RsLWOSKDKCLeN5AOB......"
        ...
    } 
}

Parsing the JSON to ABAP

SAP provides two classes /ui2/cl_json and /ui2/cl_data_access to work with JSONs and there are also many cool tools on https://dotabap.org/ for that.
Because it’s just a simple JSON I tried to avoid importing another class to the system. So I stayed with SAPs classes.

First deserialize the JSON with /ui2/cl_json.

    " Constants for properties
    CONSTANTS gc_filecontent TYPE string VALUE 'FILECONTENT' ##NO_TEXT.
    CONSTANTS gc_filename    TYPE string VALUE 'FILENAME' ##NO_TEXT.
    CONSTANTS gc_doc_cat     TYPE string VALUE 'DOCUMENTCATEGORY' ##NO_TEXT.
   
    DATA: lr_data TYPE REF TO data.
    /ui2/cl_json=>deserialize( EXPORTING json = lv_responce  "the repsonse contains the json string
                               CHANGING  data = lr_data ).

I found three similiar ways to use the class /ui2/cl_data_access to get the relevant data out of the JSON.

1. Using the class construktor and the value( ) method for earch property.

    DATA: lv_filecontent_base64 TYPE string,
          lv_filename           TYPE string,
          lv_documentcategory   TYPE string.

    /ui2/cl_data_access=>create( ir_data = lr_data iv_component = |D-{ gc_filecontent }| )->value( IMPORTING ev_data = lv_filecontent_base64 ).
    /ui2/cl_data_access=>create( ir_data = lr_data iv_component = |D-{ gc_filename    }| )->value( IMPORTING ev_data = lv_filename).
    /ui2/cl_data_access=>create( ir_data = lr_data iv_component = |D-{ gc_doc_cat     }| )->value( IMPORTING ev_data = lv_documentcategory ).

2. Create an instance as first step and pass the component. Reuse the instance with the value( ) method.

    DATA: lv_filecontent_base64 TYPE string,
          lv_filename           TYPE string,
          lv_documentcategory   TYPE string.

    DATA(lo_data_access) = /ui2/cl_data_access=>create( ir_data      = lr_data
                                                        iv_component = |D-| ).
    
    lo_data_access->at( |{ gc_filecontent }| )->value( IMPORTING ev_data = lv_filecontent_base64 ).
    lo_data_access->at( |{ gc_filename    }| )->value( IMPORTING ev_data = lv_filename ).
    lo_data_access->at( |{ gc_doc_cat     }| )->value( IMPORTING ev_data = lv_documentcategory ).

3. Use the ref( ) method to get a reference of a property value. Because it returns a generic data type (and you cannot dereference generic references) you have to use CAST combined with dereferencing (->*) to get the concret value.

    DATA(lo_data_access) = /ui2/cl_data_access=>create( ir_data      = lr_data
                                                        iv_component = |D-| ).

    DATA(lv_filecontent_base64) = CAST string( lo_data_access->at( gc_filecontent )->ref( ) )->*.
    DATA(lv_filename)           = CAST string( lo_data_access->at( gc_filename    )->ref( ) )->*.
    DATA(lv_documentcategory)   = CAST string( lo_data_access->at( gc_doc_cat     )->ref( ) )->*.

In the end I stayed with version 3 because I prefere using inline declarations. The complete result looked like this:

    " Constants for properties
    CONSTANTS gc_filecontent TYPE string VALUE 'FILECONTENT' ##NO_TEXT.
    CONSTANTS gc_filename    TYPE string VALUE 'FILENAME' ##NO_TEXT.
    CONSTANTS gc_doc_cat     TYPE string VALUE 'DOCUMENTCATEGORY' ##NO_TEXT.

    DATA: lr_data TYPE REF TO data.
    /ui2/cl_json=>deserialize( EXPORTING json = lv_response  "the repsonse contains the json string
                               CHANGING  data = lr_data ).

    DATA(lo_data_access) = /ui2/cl_data_access=>create( ir_data      = lr_data
                                                        iv_component = |D-| ).

    DATA(lv_filecontent_base64) = CAST string( lo_data_access->at( gc_filecontent )->ref( ) )->*.
    DATA(lv_filename)           = CAST string( lo_data_access->at( gc_filename    )->ref( ) )->*.
    DATA(lv_documentcategory)   = CAST string( lo_data_access->at( gc_doc_cat     )->ref( ) )->*.

    " Decode BASE64 PDF to XString
    DATA(lv_decodedx) = cl_http_utility=>if_http_utility~decode_x_base64( lv_filecontent_base64 ).
    " XString to binary
    DATA(lt_data)     = cl_bcs_convert=>xstring_to_solix( lv_decodedx ).

    " Download file
    cl_gui_frontend_services=>gui_download( EXPORTING bin_filesize         = xstrlen( lv_decodedx )
                                                      filename             = lv_filename
                                                      filetype             = 'BIN'
                                                      show_transfer_status = ' '
                                             CHANGING data_tab             = lt_data ).

When /ui2/cl_data_access is not available (SAP_UI has to be at least 7.51, see note 2526405), you can do it the oldschool way.

    " Constants for properties
    CONSTANTS gc_filecontent TYPE string VALUE 'FILECONTENT' ##NO_TEXT.
    CONSTANTS gc_filename    TYPE string VALUE 'FILENAME' ##NO_TEXT.
    CONSTANTS gc_doc_cat     TYPE string VALUE 'DOCUMENTCATEGORY' ##NO_TEXT.

    DATA: lr_data TYPE REF TO data.
    /ui2/cl_json=>deserialize( EXPORTING json = lv_response  "the repsonse contains the json string
                               CHANGING  data = lr_data ).

    ASSIGN lr_data->* TO FIELD-SYMBOL(<fs_d>).
    ASSIGN COMPONENT 'D' OF STRUCTURE <fs_d> TO FIELD-SYMBOL(<fs_components>).

    ASSIGN <fs_components>->* TO FIELD-SYMBOL(<fs_fields>).
    ASSIGN COMPONENT gc_doc_cat     OF STRUCTURE <fs_fields> TO FIELD-SYMBOL(<documentcategory>).
    ASSIGN COMPONENT gc_filename    OF STRUCTURE <fs_fields> TO FIELD-SYMBOL(<filename>).
    ASSIGN COMPONENT gc_filecontent OF STRUCTURE <fs_fields> TO FIELD-SYMBOL(<filecontent>).

    ASSIGN <documentcategory>->* TO FIELD-SYMBOL(<documentcategory_value>).
    ASSIGN <filename>->*         TO FIELD-SYMBOL(<filename_value>).
    ASSIGN <filecontent>->*      TO FIELD-SYMBOL(<filecontent_value>).

    "...

[ABAP] Workflow mail step -> Add attachment

Recently I got the demand to enhance the leave request approvel workflow with some mail steps. These mails should also include the attachments, which can be uploaded in the “Leave Request” Fiori App.

To achive this, I used the exit functionality in the mail step.

There you have to provide a class name. The class has to implement the following interface:

IF_SWF_IFS_WORKITEM_EXIT

You will get a method you can implement.

This Method has two parameters, the “Event Name” and the “Workitem Context”.

With the event, you are able to control, in which situations your exit should be fired. In my case, I just need my code run when the workitem is created (event “CREATED”). You’ll find all usable events in domain SWW_EVTTYP.

To get and pass back the attachment to the mail step, a few things has to be done.
First get the curent workitem container and check if there is already any attachment. If not, read the request id from the the leave request. With this request id, you are able to find the attachment you need. I’ve already wrote a method for that, you’ll find below. Then convert the xstring to a solix table, create the attachment document with function module “SO_DOCUMENT_INSERT_API1″ and ” SWO_CREATE” and finally pass it to the container.

 METHOD if_swf_ifs_workitem_exit~event_raised.

    DATA: lv_container     TYPE REF TO if_swf_ifs_parameter_container,
          lv_attach        TYPE TABLE OF obj_record,
          lv_folder_id     TYPE soodk,
          wa_document_info TYPE sofolenti1,
          lv_data          TYPE sodocchgi1,
          lv_objtype       TYPE swo_objtyp,
          lv_objkey        TYPE swo_typeid,
          lv_return        TYPE swotreturn,
          lv_sofm          TYPE swo_objhnd,
          lv_objject       TYPE obj_record,
          tb_obj           TYPE TABLE OF obj_record,
          it_solix_tab1    TYPE solix_tab,
          req_id           TYPE tim_req_id,
          lv_doc_type      TYPE so_obj_tp.

    CHECK im_event_name = 'CREATED'.

* Fetch Container

    lv_container = im_workitem_context->get_wi_container( ).

* Read attachment to confirm that there is no duplication

    TRY.
        lv_container->get(
          EXPORTING
            name  = '_ATTACH_OBJECTS'
          IMPORTING
            value = lv_attach ).

      CATCH: cx_swf_cnt_elem_not_found,
             cx_swf_cnt_elem_type_conflict,
             cx_swf_cnt_unit_type_conflict,
             cx_swf_cnt_container.
    ENDTRY.

    CHECK lv_attach IS INITIAL.

    CALL FUNCTION 'SO_FOLDER_ROOT_ID_GET'
      EXPORTING
        owner     = sy-uname
        region    = 'B'
      IMPORTING
        folder_id = lv_folder_id.

* Get Request ID

    lv_container->get(
      EXPORTING
        name       = 'RequestId'        
      IMPORTING
        value      = req_id ).          

* Get XSTRING of attachment

    zcl_xxx=>get_req_attachment(
      EXPORTING
        iv_req_id     = req_id                
      IMPORTING
        ev_xstring    = DATA(xstring)
        es_attachment = DATA(ls_attachment) ).

    CHECK xstring IS NOT INITIAL.

* Get document type

    SELECT SINGLE doc_type FROM toadd INTO @lv_doc_type
       WHERE mimetype EQ @ls_attachment-file_type.
    IF sy-subrc NE 0.
      lv_doc_type = 'PDF'. "If doc_type not found, at least try with pdf.
    ENDIF.

* Create and set document

    it_solix_tab1 = cl_document_bcs=>xstring_to_solix( xstring ).

* Creating First attachment

    lv_data-obj_name   = ls_attachment-file_name.
    lv_data-obj_descr  = ls_attachment-file_name.
    lv_data-obj_langu  = sy-langu.
    lv_data-sensitivty = 'P'.
*    lv_data-doc_size   = ls_attachment-file_size.

    CALL FUNCTION 'SO_DOCUMENT_INSERT_API1'
      EXPORTING
        folder_id                  = lv_folder_id
        document_data              = lv_data
        document_type              = lv_doc_type
      IMPORTING
        document_info              = wa_document_info
      TABLES
        contents_hex               = it_solix_tab1
      EXCEPTIONS
        folder_not_exist           = 1
        document_type_not_exist    = 2
        operation_no_authorization = 3
        parameter_error            = 4
        x_error                    = 5
        enqueue_error              = 6
        OTHERS                     = 7.

* Populate object type and object key for create an instance

    lv_objtype = 'SOFM'.
    lv_objkey  = wa_document_info-doc_id.

    CALL FUNCTION 'SWO_CREATE'
      EXPORTING
        objtype           = lv_objtype
        objkey            = lv_objkey
      IMPORTING
        object            = lv_sofm
        return            = lv_return
      EXCEPTIONS
        no_remote_objects = 1
        OTHERS            = 2.

* Prepare for attaching the object to container

    lv_objject-header  = 'OBJH'.
    lv_objject-type    = 'SWO'.
    lv_objject-handle  = lv_sofm.
    APPEND lv_objject TO tb_obj.

*—can be used for other workitems

    lv_container->set(
      EXPORTING
        name  = '_ATTACH_OBJECTS'
        value = tb_obj[] ).

*–this will add the attachment to email

    lv_container->set(
      EXPORTING
        name  = 'ATTACHMENTS'
        value = tb_obj[] ).

* Commit the changes

    im_workitem_context->do_commit_work( ).

  ENDMETHOD.

The following function modules are needed to read the leave request attachment:

  METHOD get_req_attachment.

    DATA: lv_has_errors     TYPE  ptreq_has_error_flag,
          lt_messages       TYPE  ptarq_uia_messages_tab,
          lt_attachments    TYPE  hress_t_ptarq_att_info,
          ex_has_attachment TYPE  boole_d.

    CALL FUNCTION 'PT_ARQ_ATTACHMENT_GET'
      EXPORTING
        im_request_id     = iv_req_id
*       IM_VERSION_NO     =
*       IM_DOCUMENT_TYPE  =
      IMPORTING
        ex_has_errors     = lv_has_errors
        ex_messages       = lt_messages
        et_attachments    = lt_attachments
        ex_has_attachment = ex_has_attachment.

    CHECK ex_has_attachment EQ abap_true.

    TRY.
        es_attachment = lt_attachments[ 1 ].
      CATCH cx_sy_itab_line_not_found.
    ENDTRY.


    CALL FUNCTION 'PT_ARQ_ATTACHMENT_DETAIL_GET'
      EXPORTING
        iv_arc_doc_id   = es_attachment-archiv_doc_id
*        iv_doc_type     =
      IMPORTING
        ex_file_content = ev_xstring
        ex_has_errors   = lv_has_errors
        ex_messages     = lt_messages.

  ENDMETHOD.