OAUTH call from ABAP

OAUTH can be called from custom ABAP. The explanation is given in this formal SAP help file. But it is quite complex.

In the example program below we will use OAUTH to call SAP BTP CPI.

First in SE80 we create a OAUTH client profile named ZOAUTH_CLIENT_PROFILE_CPI:

Then the rest of the ABAP coding is according to the SAP help file, including the error handling on issues you might face.

*&--------------------------------------------------------------------*
*& Report Z_CALL_API_USING_OAUTH
*&--------------------------------------------------------------------*
*&
*&--------------------------------------------------------------------*

REPORT z_call_api_using_oauth.

PARAMETERS:
  zp_url   TYPE string                    LOWER CASE
                                          DEFAULT 'https://apimanagement.eu10.hana.ondemand.com/v1/api/hc/csap/call_name',
  zp_sslid TYPE strustssl-applic          DEFAULT 'ANONYM',
  zp_profl TYPE oa2c_profiles-profile     DEFAULT 'ZOAUTH_CLIENT_PROFILE_CPI',
  zp_confg TYPE oa2c_client-configuration DEFAULT 'ZOAUTH_CLIENT_PROFILE_CPI'.

CONSTANTS:
  BEGIN OF zgcs_create_return,
    argument_not_found TYPE sy-subrc VALUE 1,
    plugin_not_active  TYPE sy-subrc VALUE 2,
    internal_error     TYPE sy-subrc VALUE 3,
    others             TYPE sy-subrc VALUE 4,
  END OF zgcs_create_return.

START-OF-SELECTION.

  " oData: restrict to two entries returned, via url
  DATA(zgv_api_url) = |{ zp_url }?$top=2|.

  cl_http_client=>create_by_url( EXPORTING  url                = zgv_api_url
                                            ssl_id             = zp_sslid
                                 IMPORTING  client             = DATA(zlo_http_client)
                                 EXCEPTIONS argument_not_found = zgcs_create_return-argument_not_found
                                            plugin_not_active  = zgcs_create_return-plugin_not_active
                                            internal_error     = zgcs_create_return-internal_error
                                            OTHERS             = zgcs_create_return-others ).

  CASE sy-subrc.
    WHEN zgcs_create_return-argument_not_found.
      MESSAGE 'Argument not found when trying to create http client instance' TYPE 'E'.
    WHEN zgcs_create_return-plugin_not_active.
      MESSAGE 'Plugin not active for creation of http client instance' TYPE 'E'.
    WHEN zgcs_create_return-internal_error.
      MESSAGE 'Internal error when trying to create http client instance' TYPE 'E'.
    WHEN zgcs_create_return-others.
      MESSAGE 'Generic error when trying to create http client instance' TYPE 'E'.
  ENDCASE.

  zlo_http_client->propertytype_logon_popup = zlo_http_client->co_disabled.

  TRY.
      DATA(zgo_oauth_client) = cl_oauth2_client=>create( i_profile       = zp_profl
                                                         i_configuration = zp_confg ).
    CATCH cx_oa2c_config_not_found.
      MESSAGE 'OAuth 2.0 Client Configuration not found' TYPE 'E'.
    CATCH cx_oa2c_config_profile_assign.
      MESSAGE 'OAuth 2.0 Client Config - Unassigned Profile' TYPE 'E'.
    CATCH cx_oa2c_kernel_too_old.
      MESSAGE 'OAuth 2.0 Client - Kernel too old' TYPE 'E'.
    CATCH cx_oa2c_missing_authorization.
      MESSAGE 'OAuth 2.0 Client missing authorization' TYPE 'E'.
    CATCH cx_oa2c_config_profile_multi.
      MESSAGE 'OAuth 2.0 Client Config - Profile assigned multiple times' TYPE 'E'.
  ENDTRY.

  " Set oAuth token to the http client
  TRY.
      zgo_oauth_client->set_token( io_http_client = zlo_http_client
                                   i_param_kind   = if_oauth2_client=>c_param_kind_header_field ).
    CATCH cx_oa2c_at_not_available
          cx_oa2c_at_expired.

      " When setting the token fails, first try and get a new token
      TRY.
          zgo_oauth_client->execute_cc_flow( ).
        CATCH cx_oa2c_badi_implementation.
          MESSAGE 'OAuth 2.0 Client BAdI Impl. Error' TYPE 'E'.
        CATCH cx_oa2c_not_supported.
          MESSAGE 'Not supported by Service Provider.' TYPE 'E'.
        CATCH cx_oa2c_not_allowed.
          MESSAGE 'OAuth 2.0 Client Runtime - Not Allowed' TYPE 'E'.
        CATCH cx_oa2c_prot_http_failure.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - HTTP Failure' TYPE 'E'.
        CATCH cx_oa2c_prot_other_error.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Other Error' TYPE 'E'.
        CATCH cx_oa2c_prot_unexpected_code.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Unexpected Code' TYPE 'E'.
        CATCH cx_oa2c_prot_http_forbidden.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - HTTP 403 - Forbidden' TYPE 'E'.
        CATCH cx_oa2c_prot_http_not_found.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - HTTP 404 - Not Found' TYPE 'E'.
        CATCH cx_oa2c_server_error.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Server Error' TYPE 'E'.
        CATCH cx_oa2c_temporarily_unavail.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Temporarily Unavailable' TYPE 'E'.
        CATCH cx_oa2c_unsupported_grant_type.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Unsupported Grant Type' TYPE 'E'.
        CATCH cx_oa2c_unauthorized_client.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Unauthorized Client' TYPE 'E'.
        CATCH cx_oa2c_invalid_scope.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Invalid Scope' TYPE 'E'.
        CATCH cx_oa2c_invalid_grant.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Invalid Grant' TYPE 'E'.
        CATCH cx_oa2c_invalid_client.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Invalid Client' TYPE 'E'.
        CATCH cx_oa2c_invalid_request.
          MESSAGE 'OAuth 2.0 Client Runtime Protocol - Invalid Request' TYPE 'E'.
        CATCH cx_oa2c_invalid_parameters.
          MESSAGE 'OAuth 2.0 Client Runtime - Invalid Parameters' TYPE 'E'.
        CATCH cx_oa2c_secstore_adm.
          MESSAGE 'OAuth 2.0 Client Runtime - SecStore Administration' TYPE 'E'.
        CATCH cx_oa2c_secstore.
          MESSAGE 'OAuth 2.0 Client Runtime - Secstore' TYPE 'E'.
        CATCH cx_oa2c_protocol_exception.
          MESSAGE 'OAuth 2.0 Client Runtime - Protocol Exception' TYPE 'E'.
      ENDTRY.

      " Set oAuth token to the http client
      TRY.
          zgo_oauth_client->set_token( io_http_client = zlo_http_client
                                       i_param_kind   = if_oauth2_client=>c_param_kind_header_field ).
        CATCH cx_oa2c_at_not_available.
          MESSAGE 'oAuth 2.0: Acces token not available' TYPE 'E'.
        CATCH cx_oa2c_at_expired.
          MESSAGE 'Access Token has expired.' TYPE 'E'.
        CATCH cx_oa2c_at_profile_not_covered.
          MESSAGE 'Access token has expired.' TYPE 'E'.
        CATCH cx_oa2c_not_supported.
          MESSAGE 'Not supported by Service Provider.' TYPE 'E'.
        CATCH cx_oa2c_badi_implementation.
          MESSAGE 'OAuth 2.0 Client BAdI Impl. Error' TYPE 'E'.
        CATCH cx_oa2c_secstore.
          MESSAGE 'OAuth 2.0 Client Runtime - Secstore' TYPE 'E'.
        CATCH cx_oa2c_invalid_parameters.
          MESSAGE 'OAuth 2.0 Client Runtime - Invalid Parameters' TYPE 'E'.
        CATCH cx_oa2c_icf_error.
          MESSAGE 'Unknown error received from ICF.' TYPE 'E'.
      ENDTRY.

    CATCH cx_oa2c_at_profile_not_covered.
      MESSAGE 'Access token has expired.' TYPE 'E'.
    CATCH cx_oa2c_not_supported.
      MESSAGE 'Not supported by Service Provider.' TYPE 'E'.
    CATCH cx_oa2c_badi_implementation.
      MESSAGE 'OAuth 2.0 Client BAdI Impl. Error' TYPE 'E'.
    CATCH cx_oa2c_secstore.
      MESSAGE 'OAuth 2.0 Client Runtime - Secstore' TYPE 'E'.
    CATCH cx_oa2c_invalid_parameters.
      MESSAGE 'OAuth 2.0 Client Runtime - Invalid Parameters' TYPE 'E'.
    CATCH cx_oa2c_icf_error.
      MESSAGE 'Unknown error received from ICF.' TYPE 'E'.
  ENDTRY.

  " From here on handle the http client for the API interaction
  zlo_http_client->request->set_version( if_http_request=>co_protocol_version_1_0 ).
  DATA(zlo_rest_client) = NEW cl_rest_http_client( io_http_client = zlo_http_client ).

" Get data from API
  TRY.
      zlo_rest_client->if_rest_client~get( ).
      " Collect response received from the REST API
      DATA(zli_response) = zlo_rest_client->if_rest_client~get_response_entity( ).
      DATA(zgv_http_status_code) = zli_response->get_header_field( `~status_code` ).
      DATA(zgv_status_reason)    = zli_response->get_header_field( `~status_reason` ).
      DATA(zgv_response_data)    = zli_response->get_string_data( ).

      " Record the response of the interface
      IF zgv_http_status_code BETWEEN 200 AND 299.
        " Success
        MESSAGE 'Call was succesful' TYPE 'S'.
      ELSE.
        MESSAGE 'Call failed' TYPE 'E'.
      ENDIF.

      WRITE / 'Response'.
      WRITE / zgv_response_data.

      " Issues with REST client must not lead to a short-dump
    CATCH cx_rest_client_exception INTO DATA(zlx_rest_client).
      IF zlx_rest_client->if_t100_message~t100key IS NOT INITIAL.
        DATA zlv_message TYPE string.
        MESSAGE ID zlx_rest_client->if_t100_message~t100key-msgid
                 TYPE 'E'
                 NUMBER zlx_rest_client->if_t100_message~t100key-msgno
                   WITH zlx_rest_client->if_t100_message~t100key-attr1
                        zlx_rest_client->if_t100_message~t100key-attr2
                        zlx_rest_client->if_t100_message~t100key-attr3
                        zlx_rest_client->if_t100_message~t100key-attr4.
      ELSE.
        MESSAGE 'Rest client Exception' TYPE 'E'.
      ENDIF.
  ENDTRY.

  zlo_http_client->close( ).

Security Services Tools

SAP offers on GitHub some extra Security Service Tools. These are custom Z ABAPs you can download and modify to your needs.

Link to GitHub:

GitHub – SAP-samples/security-services-tools: If you use security-related services and tools such as EWA, SOS, System Recommendations, Configuration Validation, or a security dashboard in SAP Solution Manager, the ABAP reports in this repository can help with further analysis and development.

Interesting programs from Security Service Tools

Some highlights from the Security Service Tools page:

  • Extensive cleanup program for weak hashes (including the password history data)
  • Workload statistics of RFC calls
  • Show SNC status of active users on application server
  • Show RFC gateway and logging settings
  • History of dynamic profile parameters
  • ….
  • Many more

SAP Focused Run LMDB and landscape management

SAP Focused Run LMDB is a great source of technical information. Especially with the new graphical view.

In SAP Focused Run LMDB is now part of Landscape Management.

LMDB administration (up to FRUN5.0)

With the LMDB administration page you can see the LMDB status:

Green is ok:

If not green, check the status for needed actions.

LMDB object maintenance

The LMDB Object Maintenance tile can be used to maintain a single LMDB entry:

Now select the system on the LMDB search screen:

And then push the button Display to go to the details:

On the left side you can choose a specific view on the system, like software, database, technical instances etc. If you click on the left side, the right side will show the details.

LMDB tools and graphical overview

The LMDB tools offer a graphical overview. First open the LDMB tools FIORI tile:

In Focused Run 5.0 there is a new tile for this:

Then select the technical system (in Focused Run 5.0 the main overview opens, and you need to select the technical systems on the left):

Now press the blue Hierarchy button to go to the graphical overview (in FRUN 5.0 simply click on the blue system name):

On the left is the graphical decomposition. On the right the details per object selected on the left side.

FRUN 5.0 landscape management

In Focused Run 5.0 there is a new tile replacing the LMDB and called Landscape Management:

The start page is an overview of all your systems and its status:

The other LMDB functions are still present on the left side of the screen.

API for LMDB

The SAP Focused Run LMDB has an API. For more details, read this blog.

LMDB updates

The LMDB updates are triggered automatically. This behavior can be changed in certain situations or even totally switched off. Read more on this SAP Focused Run export portal page. See also OSS note 3376303 – Support switch for disabling Agent deployments triggered by LMDB events for older versions.

Data archiving: customer and vendor master data

This blog will explain how to archive customer and vendor master data via objects FI_ACCRECV and FI_ACCPAYB. Generic technical setup must have been executed already, and is explained in this blog.

Most use of this archiving is when customers and vendors are created wrongly, to get them deleted from the system.

The below is mainly focusing on traditional ECC system. In S4HANA system both customers and vendors are integrated as business partners. For archiving sections of business partners for customer and / or vendors, read OSS note 3321585 – Archiving for Business Partner and Customer / Suppliers.

If you also want to archive/delete the LFC1 and KNC1 tables, also implement the FI_TF_DEB and FI_TF_CRE archiving objects.

Object FI_ACCRECV (customers)

Go to transaction SARA and select object FI_ACCRECV (customers).

Dependency schedule:

A lot of dependencies. Everywhere a customer number is used in an object. This makes it almost impossible to archive a customer master record. But still: it can be done to delete wrongly created master data if no transaction data is created yet.

Main tables that are archived:

  • KNA1: General customer master data
  • KNB1: Company code specific customer master data

Object FI_ACCPAYB (vendors)

Go to transaction SARA and select object FI_ACCPAYB (vendors).

Dependency schedule:

Quite some dependencies. Everywhere a customer number is used in an object. This makes it almost impossible to archive a vendor master record. But still: it can be done to delete wrongly created master data if no transaction data is created yet.

Main tables that are archived:

  • LFA1: General vendor master data
  • LFB1: Company code specific vendor master data

Technical programs and OSS notes

Write program customers: FI_ACCRECV_WRI

Delete program customers: FI_ACCRECV_DEL

Write program vendors: FI_ACCPAYB_WRI

Delete program vendors: FI_ACCPAYB_DEL

Relevant OSS notes:

Application specific customizing

There is no application specific customizing for customer and vendor archiving. You can use XD06 for customer master deletion flag setting and XK06 for vendor master deletion flag setting.

Executing the write run and delete run Customers

For customers: in transaction FI_ACCRECV select the write run:

Important is the consideration of the validation links and the deletion indicator. Customer deletion indicator flag can be set with transaction XD06.

Select your data, save the variant and start the archiving write run.

There is a sequence inconsistency. The online help has sequence FI, SD, general. The OSS note 788105 - Archiving FI_ACCRECV has sequence SD, FI, general.

You have to do the run three times: for FI, SD and general.

Deletion run is standard by selecting the archive file and starting the deletion run.

Executing the write run and delete run Vendors

For customers: in transaction FI_ACCPAYB select the write run:

Important is the consideration of the validation links and the deletion indicator. Vendor deletion indicator flag can be set with transaction XK06.

Select your data, save the variant and start the archiving write run.

You have to do the run three times: for FI, MM and general. A sequence is not given in OSS note, nor in online help.

Deletion run is standard by selecting the archive file and starting the deletion run.

Load balancing analysis tool

With SAP note 3515065 – Load Balancing Analysis, SAP delivers a new load balancing analysis tool.

Prerequisites

There are 2 prerequisites for the new load balancing analysis tool to work:

  1. Install OSS note 3515065 – Load Balancing Analysis
  2. Make sure snapshot monitoring is active (read this blog on activation)

Running the tool

To start the tool go to transaction SE38 and start program /SDF/RSLOADANALYSIS.

Selection screen:

Select the date range you want to analyze. The delta factor is normally 10 but bit too low. Increase it for more realistic result. This is factor to conclude if balancing is ok or not. Only 10% difference from average is too idealistic.

Output screen has 3 parts.

The first part is the load balancing analysis.

An overview is given on batch server groups, logon groups and RFC server groups. You can see which groups are defined, and how they are distributed over the application servers.

The second part is the work process analysis part.

Here you can see how load is distributed over the application servers using the snapshot monitoring statistics. The central instance can be excluded from the load balancing and hence show as ‘not balanced’.

The third part is host machine data.

Here you can see if the servers are having equal CPU power and memory. If no data for a sever: check in ST06 if it is configured properly.

It can be that CPU and memory are identical, but that older infrastructure was used. Then the CPU and mem look the same, but there can still be significant difference in CPU speed and memory speed. To rule this out, run the ABAPMETER tool.

SAP GUI for slow or remote network

Sometimes SAP users are far away from the server. There is much latency. For a global SAP system this is unavoidable. In some cases there might be a remote location you need to support which has a slow and/or low bandwidth connection.

In that case you best setup the SAP GUI to use

Default is as above. For low speed users, ask them to select the Low Speed Connection.

Some minor usability functions will be lost (see OSS note 161053 – Use of SAP GUI in WAN – SAP for Me):

But overall, the performance gain will outweigh normally these minor setbacks.

SAP help file: reference.

/SDF/SMON_DISPLAY to display snapshot monitoring data

The snapshot monitor tool is capturing a lot of good data. Displaying it can be bit harder. Here is where the /SDF/SMON_DISPLAY is helping.

Generic OSS note for this display is: 3210905 – Display Snapshot Monitor Data.

Setting link to plotly upfront

Before /SDF/SMON_DISPALY is working, you have to set a link to the plotly library. You can do this for all users, or for your personal user by setting a SU3 parameter:

Using /SDF/SMON_DISPLAY

Simply start transaction /SDF/SMON_DISPLAY:

Fill out the measurements you want to see. And the last n minutes. Automatically the results are shown in a separate window:

Extra enhanced functions

Extra functions are released in new OSS notes:

SICF tips and trikcs

SICF is an abbreviation for SAP internet communication framework.

It is used to expose internet services like SAP ABAP webdynpro, ODATA etc.

Checking active services

As per SAP “Note 1555208 – ICF services become inactive after upgrade or SP update” you can find the list of active services with the report RS_ICF_SERV_ADMIN_TASKS (choose option Export of Active Services into CSV file).

On table level: Check the table ICFSERVLOC. All active services are marked with an “X” flag.

Checking SICF security settings

Don’t use the old program RSICFCHK (see OSS note 3300857 – Report RSICFCHK shows incomplete result). Use the new SECSTORE transaction. At the start of transaction SECSTORE choose in the check entries section “ICF Service”:

Now hit execute and check the results:

Mass processing

SICF mass processing is done via program RS_ICF_SERV_MASS_PROCESSING.

Logging of SICF changes

To enable logging of SICF changes: switch on table logging for table ICFSERVLOC.

Various OSS notes around SICF

SAP Focused Run API’s

SAP Focused Run offers some nice API’s that you can use and re-use.

API’s available:

  • LMDB API
  • Work mode management API
  • Guided procedure API
  • Advanced analytics API

LMDB API

The LMDB now has a REST API available to read data in structured way. You can search for hosts, technical systems, software components, installed product versions and instances.

The full specification for this API can be found on this link.

Ad hoc work mode creation via function module

Via function module FM_START_ADHOC_WORKMODE you can create an ad-hoc work mode to stop monitoring for a system. You can start monitoring again by stopping the work mode by calling function module FM_STOP_ADHOC_WORKMODE.

The full specification of all the work mode API’s can be found in the PDF attached to OSS note 2508346 – Work Mode Management API Documentation for Focused Run.

Triggering guided procedure via function module

Function module FM_EXTRN_GP_EXEC can be used to call a guided procedure. Unfortunately, you need to pass the GUID of the guided procedure to the function module.

The full guided procedure API can be found on this SAP page.

Advanced Analytics API

The specification for the Advanced Analytics API can be found here.

Service Availability Management API

The Service Availability Management has webservices available as API. The specifications can be found here.

User based debugging

In some cases you need to debug the session of another user. This can be needed for example when you need to solve an issue in ABAP for a FIORI app. The end user is doing his work until the break point is reached. Then you take over the session using the normal debugging tools. The basic principle is explained in OSS note 1919888 – Debugging the applications of another user, and in this SAP help file.

Prerequisites:

Then let the user start the work. You will take over as soon as the break point is reached.

Checklist for issues can be found in OSS note 2462481 – External debug / breakpoint is not recognized.

Set the user ID to be debugged

For your user ID choose the menu option Utilities/Settings. Then select main tab ABAP editor and subtab Debugging:

Now replace your user with the user name for which you want to take the session over using the external break point.