Category: ABAP Programs

  • Create a SAP ABAP Project using ChatGPT

    What are SAP ABAP Projects, and why do we need them?

    SAP ABAP (Advanced Business Application Programming) is a programming language used to develop applications for the SAP software platform. SAP ABAP projects are collections of development objects and programs that are created, tested, and deployed as a unit.

    There are several reasons why SAP ABAP projects are necessary:

    1. Organization: SAP ABAP projects provide a structured way to organize and manage development objects and programs. This makes it easier to keep track of changes, collaborate with team members, and manage version control.
    2. Reusability: SAP ABAP projects make it easier to reuse code and development objects across different projects. This reduces the time and effort required for development and maintenance and helps ensure consistency and quality in the code.
    3. Deployment: SAP ABAP projects provide a convenient way to deploy code and development objects from one system to another. This makes it easier to test and roll out changes to production systems.
    4. Integration: SAP ABAP projects enable integration with other SAP components and systems, such as SAP HANA and SAP Fiori. This allows for the development of custom applications that can interact with other SAP systems and components.

    Overall, SAP ABAP projects are an essential tool for organizations that use SAP software, as they help streamline and optimize the development, deployment, and management of custom applications.

    How to do setup for SAP ABAP Development IDE?

    Here is a high-level overview of the steps to set up an SAP ABAP development environment:

    1. Obtain an SAP system: You will need an SAP system to develop and test your ABAP code. This can be either an SAP Developer Edition, which is a free version of SAP for development purposes, or a full-fledged SAP system from a service provider.
    2. Install an ABAP Development Tools (ADT) or ABAP in Eclipse: To develop ABAP code, you need a development environment. SAP provides the ABAP Development Tools (ADT) in Eclipse, which is a free development environment that you can use to develop and test ABAP code.
    3. Create a Development Project: Once you have the ABAP Development Tools installed, you can create a new development project. This project will contain all the development objects and programs that you create as part of your development work.
    4. Develop and Test your Code: You can now start developing and testing your ABAP code within the development project. The ABAP Development Tools provide a range of features, such as syntax highlighting, code completion, and debugging, to help you in this process.
    5. Deploy your Code: Once you have completed your development work and thoroughly tested your code, you can deploy your code to the SAP system. This can be done using the ABAP Development Tools or through the SAP GUI.
    6. Maintenance and Updates: Over time, you may need to make changes to your code or add new features. The ABAP Development Tools provide a range of features for maintaining and updating your code, such as version control and code comparison.

    This is just a high-level overview of the setup process for SAP ABAP development. The exact steps will depend on the specifics of your system and environment, but the ABAP Development Tools provide extensive documentation and support to help you get started.

    How to use ChatGPT to create an SAP ABAP Project?

    Step 01: Visit ChatGPT Portal: https://chat.openai.com/chat

    Step 02: Type your query; you can ask regarding a single step related to your UI5 issue or can ask ChatGPT to generate code for the entire project. We will ask ChatGPT to create a project with table forms and CRUD operations.

    Step 03: We asked ChatGPT to create an SAP ABAP Report that takes two input and have the option to do sum, subtraction, multiple, and deletion of the entered numbers. We got the given output:

    generate abap code using chatgpt

    Here is an example of an SAP ABAP report that takes two input values, performs arithmetic operations on them based on the user’s selection, and outputs the result (In our case, we have create a Report in SE38 and named it ZCHATGPTGEN):

    REPORT ZCHATGPTGEN.
    
    
    PARAMETERS p_num1 TYPE n.
    PARAMETERS p_num2 TYPE n.
    
    CONSTANTS : rbSelected TYPE c LENGTH 1 VALUE 'X'.
    
    DATA : p_txt type c LENGTH 100.
    
    SELECTION-SCREEN BEGIN OF BLOCK frame1 WITH FRAME TITLE text-001.
      SELECTION-SCREEN ULINE /10(40).
    
      SELECTION-SCREEN BEGIN OF LINE.
        SELECTION-SCREEN POSITION 15.
        PARAMETERS: rb1 RADIOBUTTON GROUP rb.
        SELECTION-SCREEN COMMENT 20(30) text-002.
      SELECTION-SCREEN END OF LINE.
    
      SELECTION-SCREEN BEGIN OF LINE.
        SELECTION-SCREEN POSITION 15.
        PARAMETERS: rb2 RADIOBUTTON GROUP rb.
        SELECTION-SCREEN COMMENT 20(30) text-003.
      SELECTION-SCREEN END OF LINE.
    
      SELECTION-SCREEN BEGIN OF LINE.
        SELECTION-SCREEN POSITION 15.
        PARAMETERS: rb3 RADIOBUTTON GROUP rb.
        SELECTION-SCREEN COMMENT 20(30) text-004.
      SELECTION-SCREEN END OF LINE.
    
       SELECTION-SCREEN BEGIN OF LINE.
        SELECTION-SCREEN POSITION 15.
        PARAMETERS: rb4 RADIOBUTTON GROUP rb.
        SELECTION-SCREEN COMMENT 20(30) text-005.
      SELECTION-SCREEN END OF LINE.
    
      SELECTION-SCREEN ULINE /10(40).
    SELECTION-SCREEN END OF BLOCK frame1.
    
    DATA: l_result TYPE n.
    
    START-OF-SELECTION.
    IF rb1 = rbSelected.
       l_result = p_num1 + p_num2.
    ELSEIF rb2 = rbSelected.
       l_result = p_num1 - p_num2.
    ELSEIF rb3 = rbSelected.
      l_result = p_num1 * p_num2.
      ELSEIF rb4 = rbSelected.
      IF p_num2 = 0.
            MESSAGE 'Division by zero is not allowed!' TYPE 'E'.
            LEAVE TO SCREEN 0.
          ENDIF.
          l_result = p_num1 / p_num2.
    ENDIF.
    
    
      WRITE: / 'Result:', l_result.

    Output

    How to use ChatGPT to create an SAP ABAP Project.

    How will ChatGPT impact ABAPer Life and Jobs?

    As a language model, OpenAI’s GPT-3, including ChatGPT, has the potential to impact various aspects of the lives and jobs of ABAP developers. Here are a few ways in which it could have an impact:

    1. Automation of repetitive tasks: GPT-3 has the ability to perform repetitive tasks, such as coding and testing, quickly and accurately. This could lead to increased efficiency and productivity, freeing up time for ABAP developers to focus on more complex and strategic tasks.
    2. Improved accuracy and quality of code: GPT-3 can provide suggestions and generate code based on natural language input. This can help reduce the likelihood of errors and improve the overall quality of the code.
    3. Assistance with documentation: GPT-3 can assist with documentation and help create comprehensive and accurate documentation for ABAP projects.
    4. Knowledge transfer: GPT-3 can help with knowledge transfer between team members and across organizations. This can help ensure that important information and best practices are shared and retained.
    5. New job opportunities: GPT-3 can also create new job opportunities, such as roles focused on developing and integrating AI solutions into SAP systems.

    It is important to note that while GPT-3 has the potential to impact ABAP developers in a number of positive ways, it is also important for organizations to consider the potential challenges and limitations of using AI technologies. Additionally, as with any technology, it is crucial for ABAP developers to continually upskill and adapt to new technologies and developments in the field.

    How can ChatGPT assist in Knowledge transfer?

    ChatGPT can assist in knowledge transfer in several ways:

    1. Natural Language Processing (NLP) based search and retrieval: ChatGPT can be used to search and retrieve relevant information based on natural language queries. This can help ABAP developers quickly find the information they need, without having to navigate through multiple sources or search engines.
    2. Documentation: ChatGPT can assist with creating and maintaining documentation for ABAP projects. It can provide information on specific topics, such as code snippets and best practices, and assist with generating documentation clearly and concisely.
    3. Q&A: ChatGPT can also act as a virtual assistant, answering questions and providing guidance to ABAP developers. This can help with knowledge transfer by providing quick access to information and helping to bridge the gap between experts and less experienced team members.
    4. Personalized learning: ChatGPT can also be used for personalized learning and training. It can provide guidance and feedback to ABAP developers, helping them to learn new skills and improve their expertise.

    By providing quick and accessible information and assistance, ChatGPT can help ABAP developers to efficiently access and transfer knowledge within their organization. This can help to improve the overall quality and efficiency of ABAP projects, as well as foster a culture of continuous learning and improvement.

    Tutorial Video

    You can watch the video below to learn implementation:

    [embedyt] https://www.youtube.com/watch?v=AzutmlntNKI[/embedyt]
  • How to Integrate ChatGPT in SAP ABAP

    Introduction

    A general idea of how to integrate ChatGPT with SAP ABAP:

    1. First, you would need to have access to an instance of the ChatGPT model, either through the OpenAI API or by running the model locally.
    2. Next, you would need to create an ABAP program that calls the ChatGPT API and passes it input text, such as a user’s question.
    3. The program would then need to handle the API response and parse the generated text output.
    4. Finally, the program would need to display the generated text in an appropriate format, such as in an SAP GUI screen or in an output file.

    Here’s an example of some code that could be used in an ABAP program to call the OpenAI API and get a response from ChatGPT:

    CALL FUNCTION 'HTTP_POST'
      EXPORTING
        url = 'https://api.openai.com/v1/engines/davinci/completions'
        encoding = 'UTF-8'
      IMPORTING
        response = l_response
      CHANGING
        data = l_data
        headers = l_headers
      EXCEPTIONS
        http_communication_failure = 1
        http_invalid_state = 2
        http_processing_failed = 3
        OTHERS = 4.
    

     

    How to Integrate ChatGPT in SAP ABAP

    As shown in below image, we will follow three simple steps to integrate ChatGPT APIs within SAP ABAP Report.

    Integrate ChatGPT in SAP ABAP

    1. Get API of Open AI

    We have already discussed all the steps involved regarding API creation in this article.

    2. Create ABAP Report

    Go to SE38, and create a new ABAP Report. Create one Input Parameter as shown below:

    ChatGPT ABAP Report

    3. Integrate ChatGPT Call

    Write the given code in your report:

    REPORT ZCHATGPT.
    
    PARAMETERS: l_ques type string.
    
    data: l_response type string,
          l_data type string,
          lv_payload_x type xstring,
          l_max_tokens type i.
    
    "l_ques = 'What is the meaning of life?'. EXAMPLE
    l_max_tokens = 50.
    l_data = '{' && '"prompt":' && '"' && l_ques && '",' && '"max_tokens":' && l_max_tokens && '}'.
    
    CALL FUNCTION 'SCMS_STRING_TO_XSTRING'
    EXPORTING
    text = l_data
    IMPORTING
    buffer = lv_payload_x.
    
       DATA: lo_http_client TYPE REF TO if_http_client.
        DATA: response TYPE string,
              lv_auth  TYPE string.
        CONSTANTS : lv_url TYPE string VALUE 'https://api.openai.com/v1/engines/davinci/completions'.
    
    
          "create HTTP client by url
          CALL METHOD cl_http_client=>create_by_url
            EXPORTING
              url                = lv_url
            IMPORTING
              client             = lo_http_client
            EXCEPTIONS
              argument_not_found = 1
              plugin_not_active  = 2
              internal_error     = 3
              OTHERS             = 4.
    
          IF sy-subrc <> 0.
            "error handling
          ENDIF.
    
          "setting request method
          lo_http_client->request->set_method('POST').
    
          "adding headers
          lo_http_client->request->set_header_field( name = 'Content-Type' value = 'application/x-www-form-urlencoded' ).
          lo_http_client->request->set_header_field( name = 'Accept' value = 'application/json' ).
          lo_http_client->request->set_header_field( name = 'Authorization' value = 'Bearer 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' ).
    
          lo_http_client->request->set_form_field(
      EXPORTING
        name  = 'prompt'                    " Name of form field
        value =   l_ques   ).
    
    
          "lo_http_client->request->set_data( lv_payload_x ).
    
          "Available Security Schemes for productive API Endpoints
          "OAuth 2.0
    
          CALL METHOD lo_http_client->send
            EXCEPTIONS
              http_communication_failure = 1
              http_invalid_state         = 2
              http_processing_failed     = 3
              http_invalid_timeout       = 4
              OTHERS                     = 5.
    
          IF sy-subrc = 0.
            CALL METHOD lo_http_client->receive
              EXCEPTIONS
                http_communication_failure = 1
                http_invalid_state         = 2
                http_processing_failed     = 3
                OTHERS                     = 5.
          ENDIF.
    
          IF sy-subrc <> 0.
            "error handling
            response = lo_http_client->response->get_cdata( ).
            l_response = response.
          ELSE.
            response = lo_http_client->response->get_cdata( ).
            IF response IS NOT INITIAL.
              l_response = response.
            ELSE.
              l_response = 'Call was successful, but got no response'.
            ENDIF.
          ENDIF.
    
    WRITE l_response.

     

    Code Explanation

    Here, I have added variables l_question and l_max_tokens to hold the user’s question and the maximum token value, respectively. I have then added these values to the l_data variable, which is passed as the data parameter in the HTTP_POST call. The response variable l_response will hold the generated text as a result of the API call.

    Here, I have created an object of class if_http_client and added the headers using the add_header_field method. Then i have passed this object as a parameter ‘manager’ in the ‘HTTP_POST’ call.

    It’s important to note that the format of the data passed to the OpenAI API must be in JSON format, so that’s why I have added the prompt and max_tokens in JSON format in the l_data variable.

    Remember to replace <YOUR_API_KEY> with the API key that you have generated using the Open AI platform.

    Output Screen

    Chat GPT integration with SAP ABAP

    Tutorial Video

    You can watch the video below to learn implementation:

    [embedyt] https://www.youtube.com/watch?v=VvEO2MDpdAc[/embedyt]
  • OOPS ALV in SAP ABAP

    Preface – This post is part of the ABAP Programs and Object Oriented ABAP series.

    Introduction

    The OO ALV is ALV using object-oriented ABAP. ALV stands for ABAP List Viewer and provides the standard list format and user interface for all the ABAP programs. The advantage of using OOPS ALV in SAP ABAP is that is flexible and used to build interactive and modern-designing list. SAP has provided a class (class name: CL_GUI_ALV_GRID) which acts as the wrapper class encapsulating ALV GRID functionality.

    The basic components for ALV Grid are:

    • List data: List data are the internal table data’s to be listed.
    • Field Catalog: The field catalog is the internal table that defines the specification on the display of fields. To generate field catalog there are three methods: Automatic generation, semi-automatic generation and manual generation. The internal table must be referred to LVC_T_FCAT.
    • Layout Structure: The layout structure must be of type “LVC_S_LAYO”. This can be used to modify the layout including colour adjustments, grid customization etc.
    • Event Handler: To handle events triggered by ALV, event handler class should be defined and implemented.
    • Additional Data: To stimulate additional data in ALV Grid, additional data should be passed as a parameter.

    Example

    Follow the steps to create an OOPS ALV in SAP ABAP:

    1. Create an object of class CL_GUI_CUSTOM_CONTAINER and class CL_GUI_ALV_GRID.
    2. Populate internal table.
    3. Call screen in which you want to display the list.
    4. Create Custom Container from layout lab
    5. Call method of class CL_GUI_ALV_GRID and pass the required parameters.

    Program

    "SCARR is the SAP Standard table which stores Airlines data
    DATA: t_flight TYPE TABLE OF SCARR.
    DATA: cust_container TYPE REF TO CL_GUI_CUSTOM_CONTAINER,
    cust_grid TYPE REF TO CL_GUI_ALV_GRID.
    Select * from SCARR into table t_flight.
    CALL screen 100.
    MODULE STATUS_0100 OUTPUT.
    SET PF-STATUS 'SCREEN1'.
    SET TITLEBAR 'AIRLINES LIST'.
    ENDMODULE.
    MODULE USER_COMMAND_0100 INPUT.
    CASE SY-UCOMM.
    WHEN 'BACK'.
    LEAVE TO SCREEN 0.
    ENDCASE.
    ENDMODULE.
    MODULE LIST OUTPUT.
    CREATE OBJECT CUST_CONTAINER
    EXPORTING
    CONTAINER_NAME = 'CONTAINER'.
    CREATE OBJECT CUST_GRID
    EXPORTING
    I_PARENT = CUST_CONTAINER.
    CALL METHOD CUST_GRID->SET_TABLE_FOR_FIRST_DISPLAY
    EXPORTING
    i_structure_name = 'SCARR'
    Changing
    it_outtab = t_flight.
    ENDMODULE.

    After you paste the above code, you need to double-click on “CALL screen 100.” so that you can create a Screen. If you try to execute without creating a screen, then you will get an exception mentioning the same, i.e., “No Screen 100 available.”

    After double-clicking the screen, you will see the below view, update info as shown below:

    OO ALV Screen

    Double click on “SET PF-STATUS ‘SCREEN1’. ” and enter these:

    Screen 1 Status

    Add a button by double-clicking on Screen 100 and performing below:

    Add a button

    Back Code

    Update and Activate the screen after changing the below:

    Flow Logic in Screen

    Now change the Layout as shown below:

    1. Click on Layouts

    Layouts

    2. Create a custom container as shown below, choose the button and draw a rectangular shape:

    Screen Painter

    3. It will create something, as shown below. Double-click on it and then enter the name as “CONTAINER”

    CONTAINER

    5. Now Activate the screen, go back to the program, activate the program and run the program, you will see the OO ALV screen as shown below:

    OO ALV Output

    Tutorial Video

    You can watch the video below to learn implementation:

    [embedyt] https://www.youtube.com/watch?v=_duuxLwTq7I[/embedyt]
  • Function Imports in SAP OData

    Preface – This post is part of the ABAP Programs series.

    DATA: ls_parameter TYPE /iwbep/s_mgw_name_value_pair,
          lv_custid    TYPE kunnr,
          lv_flag      TYPE char1,
          lt_custinfo  TYPE TABLE OF ztest_gw_srv,
          ls_custinfo  TYPE ztest_gw_srv,
          ls_entity    TYPE zcl_ztest_gw_srv_mpc=>ts_msg_return.
    
    
        IF iv_action_name = 'demoFuncImport'. " Check what action is being requested
          IF it_parameter IS NOT INITIAL.
    
    * Read Function import parameter value
            READ TABLE it_parameter INTO ls_parameter WITH KEY name = 'CustId'.
            IF sy-subrc = 0.
              lv_custid = ls_parameter-value.
            ENDIF.
    
            READ TABLE it_parameter INTO ls_parameter WITH KEY name = 'Approved_Flag'.
            IF sy-subrc = 0.
              lv_flag = ls_parameter-value.
            ENDIF.
    
            IF  lv_custid IS NOT INITIAL.
              UPDATE ztest_gw_srv SET approved = lv_flag WHERE cust_id = lv_custid.
              IF sy-subrc = 0.
                ls_entity-type   = 'S'.
                ls_entity-message = 'Customer info successfully approved'.
              ELSE.
                ls_entity-type   = 'E'.
                ls_entity-message = 'Error'.
              ENDIF.
    
    
    * Call method copy_data_to_ref and export entity set data
              copy_data_to_ref( EXPORTING is_data = ls_entity
                      CHANGING cr_data = er_data ).
    
            ENDIF.
          ENDIF.
        ENDIF.

     

  • Convert JSON to ABAP Internal Table

    Preface – This post is part of the ABAP Programs series.

     TYPES:
            BEGIN OF t_entry,
              access_token TYPE string,
              token_type   TYPE string,
              expires_in   TYPE n LENGTH 8,
              scope        TYPE string,
              jti          TYPE string,
            END OF t_entry .
          TYPES:
            t_entry_map TYPE SORTED TABLE OF t_entry WITH UNIQUE KEY access_token.
          DATA: m_entries TYPE t_entry.
    
          DATA: lr_instance  TYPE REF TO  /ui5/cl_json_parser.
          CREATE OBJECT lr_instance.
          CALL METHOD me->get_token.
          IF gv_token IS NOT INITIAL.
    
    *        data: itab TYPE TABLE OF string.
    *        data: access_tok type string.
    *        SPLIT gv_token at '"' INTO TABLE itab.
    *        try.
    *            lv_auth2 = itab[ 4 ].
    *          catch cx_sy_itab_line_not_found.
    *        ENDTRY.
    
            /ui2/cl_json=>deserialize(
            EXPORTING json = gv_token pretty_name = /ui2/cl_json=>pretty_mode-camel_case CHANGING data = m_entries ).
            lv_auth2 = m_entries-access_token.
            gv_token = gv_token+17.

     

  • Create Object History in SAP Blockchain

    Preface – This post is part of the Blockchain on SAP Cloud Platform and ABAP Programs series.

    In this article, we will learn how to create a block in Blockchain on the SAP Cloud Platform.

     METHOD create_object_history.
        DATA: lo_http_client TYPE REF TO if_http_client.
        DATA: response TYPE string,
              lv_url   TYPE string,
              lv_auth  TYPE string.
        CONSTANTS : lv_initial_url TYPE string VALUE '<Your_Service>'.
    
        IF iv_object_id IS NOT INITIAL.
    *** Getting Token
          TYPES:
            BEGIN OF t_entry,
              access_token TYPE string,
              token_type   TYPE string,
              expires_in   TYPE n LENGTH 8,
              scope        TYPE string,
              jti          TYPE string,
            END OF t_entry .
          TYPES:
            t_entry_map TYPE SORTED TABLE OF t_entry WITH UNIQUE KEY access_token.
          DATA: m_entries TYPE t_entry.
    
          DATA: lr_instance  TYPE REF TO  /ui5/cl_json_parser.
          CREATE OBJECT lr_instance.
          CALL METHOD me->get_token.
          IF gv_token IS NOT INITIAL.
    
            /ui2/cl_json=>deserialize(
            EXPORTING json = gv_token pretty_name = /ui2/cl_json=>pretty_mode-camel_case CHANGING data = m_entries ).
            DATA lv_auth2 TYPE string.
            lv_auth2 = m_entries-access_token.
    *        gv_token = gv_token+17.
    
            CONCATENATE 'Bearer' lv_auth2 INTO lv_auth SEPARATED BY space.
    
          ENDIF.
          DATA lv_object_id TYPE string.
          lv_object_id = iv_object_id.
          TRANSLATE lv_object_id TO LOWER CASE.
    
          CONCATENATE lv_initial_url lv_object_id INTO lv_url. "Appending Fix URL and the Object ID to get the Request URL
    
          "create HTTP client by url
          CALL METHOD cl_http_client=>create_by_url
            EXPORTING
              url                = lv_url
            IMPORTING
              client             = lo_http_client
            EXCEPTIONS
              argument_not_found = 1
              plugin_not_active  = 2
              internal_error     = 3
              OTHERS             = 4.
    
          "Available API Endpoints
          "https://blockchain-service.cfapps.sap.hana.ondemand.com/blockchain/proofOfHistory/api/v1
          "https://blockchain-service.cfapps.eu10.hana.ondemand.com/blockchain/proofOfHistory/api/v1
          "https://blockchain-service.cfapps.us10.hana.ondemand.com/blockchain/proofOfHistory/api/v1
    
          IF sy-subrc <> 0.
            "error handling
          ENDIF.
    
          "setting request method
          lo_http_client->request->set_method('POST').
    
          "adding headers
          lo_http_client->request->set_header_field( name = 'Content-Type' value = 'application/x-www-form-urlencoded' ).
          lo_http_client->request->set_header_field( name = 'Accept' value = 'application/json' ).
          lo_http_client->request->set_header_field( name = 'Authorization' value = lv_auth ).
    
          "Available Security Schemes for productive API Endpoints
          "OAuth 2.0
    
          CALL METHOD lo_http_client->send
            EXCEPTIONS
              http_communication_failure = 1
              http_invalid_state         = 2
              http_processing_failed     = 3
              http_invalid_timeout       = 4
              OTHERS                     = 5.
    
          IF sy-subrc = 0.
            CALL METHOD lo_http_client->receive
              EXCEPTIONS
                http_communication_failure = 1
                http_invalid_state         = 2
                http_processing_failed     = 3
                OTHERS                     = 5.
          ENDIF.
    
          IF sy-subrc <> 0.
            "error handling
            response = lo_http_client->response->get_cdata( ).
            ev_response = response.
          ELSE.
            response = lo_http_client->response->get_cdata( ).
            IF response IS NOT INITIAL.
              ev_response = response.
            ELSE.
              ev_response = 'Block created successfully'.
            ENDIF.
          ENDIF.
        ENDIF.
      ENDMETHOD.
    

     

  • Get Proof history from the Blockchain Service using SAP ABAP

    Preface – This post is part of the Blockchain on SAP Cloud Platform and ABAP Programs series.

    In this step, we will call the blockchain service again using the token that we have stored in above step. And then we will receive the history of transactions from blockchain.

    METHOD get_proof_history.
        DATA: lo_http_client TYPE REF TO if_http_client.
        DATA: response TYPE string,
              lv_url   TYPE string,
              lv_auth  TYPE string,
              lv_auth2 TYPE string.
        CONSTANTS : lv_initial_url TYPE string VALUE '<Your Service>'.
        IF iv_object_id IS NOT INITIAL.
    *** Getting Token
          TYPES:
            BEGIN OF t_entry,
              access_token TYPE string,
              token_type   TYPE string,
              expires_in   TYPE n LENGTH 8,
              scope        TYPE string,
              jti          TYPE string,
            END OF t_entry .
          TYPES:
            t_entry_map TYPE SORTED TABLE OF t_entry WITH UNIQUE KEY access_token.
          DATA: m_entries TYPE t_entry.
          DATA: lr_instance  TYPE REF TO  /ui5/cl_json_parser.
          CREATE OBJECT lr_instance.
          CALL METHOD me->get_token.
          IF gv_token IS NOT INITIAL.
    *        data: itab TYPE TABLE OF string.
    *        data: access_tok type string.
    *        SPLIT gv_token at '"' INTO TABLE itab.
    *        try.
    *            lv_auth2 = itab[ 4 ].
    *          catch cx_sy_itab_line_not_found.
    *        ENDTRY.
            /ui2/cl_json=>deserialize(
            EXPORTING json = gv_token pretty_name = /ui2/cl_json=>pretty_mode-camel_case CHANGING data = m_entries ).
            lv_auth2 = m_entries-access_token.
            gv_token = gv_token+17.
            CONCATENATE 'Bearer' lv_auth2 INTO lv_auth SEPARATED BY space.
          ENDIF.
          DATA lv_object_id TYPE string.
          lv_object_id = iv_object_id.
          TRANSLATE lv_object_id TO LOWER CASE.
          CONCATENATE lv_initial_url lv_object_id INTO lv_url. "Appending Fix URL and the Object ID to get the Request URL
          "create HTTP client by url
          CALL METHOD cl_http_client=>create_by_url
            EXPORTING
              url                = lv_url
            IMPORTING
              client             = lo_http_client
            EXCEPTIONS
              argument_not_found = 1
              plugin_not_active  = 2
              internal_error     = 3
              OTHERS             = 4.
          "Available API Endpoints
          "https://blockchain-service.cfapps.sap.hana.ondemand.com/blockchain/proofOfHistory/api/v1
          "https://blockchain-service.cfapps.eu10.hana.ondemand.com/blockchain/proofOfHistory/api/v1
          "https://blockchain-service.cfapps.us10.hana.ondemand.com/blockchain/proofOfHistory/api/v1
          IF sy-subrc <> 0.
            "error handling
          ENDIF.
          "setting request method
          lo_http_client->request->set_method('GET').
          "creatung Auth value
    *       lv_auth2 = 'Basic <Your Login Credentials>'.
          "adding headers
    *      lo_http_client->request->set_header_field( name = 'Content-Type' value = 'application/x-www-form-urlencoded' ).
          lo_http_client->request->set_header_field( name = 'Accept' value = 'application/json' ).
          lo_http_client->request->set_header_field( name = 'Authorization' value = lv_auth ).
    *      lo_http_client->request->set_header_field( name = 'APIKey' value = 'zBoCpDtkaT9jexRjtMk0J98Rs8izmQi1' ).
          "Available Security Schemes for productive API Endpoints
          "OAuth 2.0
          CALL METHOD lo_http_client->send
            EXCEPTIONS
              http_communication_failure = 1
              http_invalid_state         = 2
              http_processing_failed     = 3
              http_invalid_timeout       = 4
              OTHERS                     = 5.
          IF sy-subrc = 0.
            CALL METHOD lo_http_client->receive
              EXCEPTIONS
                http_communication_failure = 1
                http_invalid_state         = 2
                http_processing_failed     = 3
                OTHERS                     = 5.
          ENDIF.
          IF sy-subrc = 1.
            "error handling
            ev_response = 'http_communication_failure'.
          ELSEIF sy-subrc = 2.
            ev_response = 'http_invalid_state'.
          ELSEIF sy-subrc = 3.
            ev_response = 'http_processing_failed'.
          ELSEIF sy-subrc = 0.
            response = lo_http_client->response->get_cdata( ).
    *WRITE: 'response: ', response.
            ev_response = response.
          ELSE.
            ev_response = 'Unknown Error'.
          ENDIF.
        ENDIF.
      ENDMETHOD.

     

  • Get Token from SAP Cloud Platform Service

    Preface – This post is part of the ABAP Programs series.

    In this step we will call the service to get the token and store that token in a global variable for later use.

    METHOD get_token.
        DATA: lo_http_client TYPE REF TO if_http_client.
        DATA: response TYPE string,
              lv_url   TYPE string.
        CONSTANTS: lv_initial_url TYPE string VALUE '<Blockchain Service Link>',
                   lv_auth        TYPE string VALUE 'Basic <your login credentials>'.
        "create HTTP client by url
        CALL METHOD cl_http_client=>create_by_url
          EXPORTING
            url                = lv_initial_url
          IMPORTING
            client             = lo_http_client
          EXCEPTIONS
            argument_not_found = 1
            plugin_not_active  = 2
            internal_error     = 3
            OTHERS             = 4.
        "Available API Endpoints
        "https://blockchain-service.cfapps.sap.hana.ondemand.com/blockchain/proofOfHistory/api/v1
        "https://blockchain-service.cfapps.eu10.hana.ondemand.com/blockchain/proofOfHistory/api/v1
        "https://blockchain-service.cfapps.us10.hana.ondemand.com/blockchain/proofOfHistory/api/v1
        IF sy-subrc <> 0.
          "error handling
        ENDIF.
        "setting request method
        lo_http_client->request->set_method('GET').
        "adding headers
        lo_http_client->request->set_header_field( name = 'Authorization' value = lv_auth ).
        "Available Security Schemes for productive API Endpoints
        "OAuth 2.0
        CALL METHOD lo_http_client->send
          EXCEPTIONS
            http_communication_failure = 1
            http_invalid_state         = 2
            http_processing_failed     = 3
            http_invalid_timeout       = 4
            OTHERS                     = 5.
        IF sy-subrc = 0.
          CALL METHOD lo_http_client->receive
            EXCEPTIONS
              http_communication_failure = 1
              http_invalid_state         = 2
              http_processing_failed     = 3
              OTHERS                     = 5.
        ENDIF.
        IF sy-subrc <> 0.
          "error handling
        ENDIF.
        response = lo_http_client->response->get_cdata( ).
       GV_TOKEN = response. "Global Variable
      ENDMETHOD.

     

  • Calculate a hash in ABAP

    Preface – This post is part of the ABAP Programs series.

    In ABAP we can perform the following:

    calculate_hash_for_raw

    METHOD calculate_hash_for_raw.
    
        TRY.
            cl_abap_message_digest=>calculate_hash_for_raw(
              EXPORTING
                if_algorithm = 'SHA256'
                if_data      = iv_data
              IMPORTING
                ef_hashstring = ev_sha256
            ).
          CATCH cx_root.
            " Eh, what're you gonna do?
        ENDTRY.
      ENDMETHOD.

    calculate_hash_for_string

    METHOD calculate_hash_for_string.
    
        TRY.
            cl_abap_message_digest=>calculate_hash_for_char(
              EXPORTING
                if_algorithm = 'SHA256'
                if_data      = iv_data
              IMPORTING
                ef_hashstring = ev_sha256
            ).
          CATCH cx_root.
            " Eh, what're you gonna do?
        ENDTRY.
      ENDMETHOD.

     

  • Type Casting in ABAP Class

    Preface – This post is part of the ABAP Programs series.

    Type Casting in ABAP Class

    Note: If you are searching for basic type casting/conversion of ABAP variable in Reports/Program, click here.

    Prerequisite:

    1. You must have a basic Idea of local class and instance/reference of class.

    2. Inheritance and Polymorphism concept

    Note: Parent Class is also called base class and Child class is also called Sub class.

    What is Static and Dynamic Type?

    Before we talk about type casting, we need to know what are static Type and Dynamic type. Each reference variable has a dynamic type and a static type.

    Suppose we have a class C1 and its child class C2.

    So, in our program we will write following code to make reference and create object.

    DATA: obj1 TYPE REF TO C1.

    Here obj1 is our reference variable and C1 is the Static Type.

    Thus anything that comes after TYPE REF TO is a static type because the object obj1 is pointing to fixed or static type [here class C1].

    Now, in our code, we proceed as below:

    CREATE OBJECT obj1.

    In this line we actually point to the class C1 using our object obj1. This pointing is called Dynamic Type and it is pointing to C1 same as the static type above.

    We can also write following code:

    CREATE OBJETC obj1 TYPE C2.

    In this line we are pointing to child class C2 of C1. This pointing is defined at runtime and called as Dynamic Type, and this time it is not same as the static type.

    Thus we conclude that Dynamic type is defined at runtime of the program while static type is declared with the declaration of reference variable. Static type can be same as Dynamic type or less specific than it [it means, it can just point to the parents and not all the child unlike the dynamic type which can].

    What is a Type casting?

    Type Casting in ABAP is just like casting in other computer languages. It is one way of inheriting the properties from either base/parent class or sub/child class into one another. It is used to cast one data type, class or Interface into another data type, class or interface.

    For data type casting, refer here.

    Definition:

    Type casting is a process of converting reference of class or interface to another, given both the class are from same hierarchy i.e. either one of them must be a parent class and the other a child class.

    Syntax:

    Destination_Ref = | ?= Source_Ref.

    Some questions for you:

    Why do we need Type casting?

    How to achieve a type casting?

    Example of Type casting

    What are types of Type Casting?

    Some Basic rules of type casting.