ABAP: execute OS level command
There are many things that one can do to execute a command in an Operating System from an ABAP report. I’ll explain one method that one can take to accomplish this.
- Using transactions SM49 and SM69 set up and test a new OS command that you wish to execute. For the purposes of this post I’ve set up an executable command ZSAPCAR32.
- When I was setting up the new command I’ve selected the option to add additional parameters to the command.
- Once tested and satisfied you can add a new function module [SXPG_COMMAND_EXECUTE] to your report that will call preset executable command.
data: g_rlog TYPE btcxpm OCCURS 0.
CALL FUNCTION 'SXPG_COMMAND_EXECUTE'
EXPORTING
commandname = 'ZSAPCAR32'
additional_parameters = <additional parameters>
operatingsystem = <system you specified in SM69>
TABLES
exec_protocol = g_rlog
EXCEPTIONS
no_permission = 1
command_not_found = 2
parameters_too_long = 3
security_risk = 4
wrong_check_call_interface = 5
program_start_error = 6
program_termination_error = 7
x_error = 8
parameter_expected = 9
too_many_parameters = 10
illegal_command = 11
wrong_asynchronous_parameters = 12
cant_enq_tbtco_entry = 13
jobcount_generation_error = 14
OTHERS = 15.
if sy-subrc eq 0.
LOOP AT g_rlog INTO g_warlog.
* display command output
write g_warlog.
ENDLOOP.
endif.
The above code will execute your OS command and display the results.
ABAP: load file using pop-up window
When writing a program the simplest way to load a file from your client PC in to the server SAP syste is through a use of a regular text box. But if you want to get a little fancier try using the following function:
data: l_select TYPE sapb-sappfad.
CALL FUNCTION 'WS_FILENAME_GET'
EXPORTING
def_filename = l_select
def_path = ' '
mask = ',*.*,*.*.'
mode = 'O'
title = 'Select filename to OPEN'(f05)
IMPORTING
filename = l_select
EXCEPTIONS
selection_cancel = 1
selection_error = 2
OTHERS = 3.
This function will open up a pop-up window [standard to windows] allowing the user to select a file somewhere on their local comptuer.
SAPGUI_PROGRESS_INDICATOR
A usefull little function that will allow you to display a status update on the bottom left corner of the screen when running your reports.
call function 'SAPGUI_PROGRESS_INDICATOR'
EXPORTING
percentage = 0
text = STATUS_TEXT.
Note: anything lower then 0 will be rounded up to 0 and anything greater then 100 will be rounded down to 100.
When was the last System Refresh done in an SAP system?
To quickly check when your DEV/QA system was refreshed from a production box perform the following steps:
- Execute the transaction SCCL
- Fill in the Source Clinet filed [ie: 001]
- Select <Goto> <Log display> from the main menu
You should see a screen with a list of dates of when the system was last refreshed.
Other useful transactions:
SCC9: client copy – copy a client
SCC8: client export
SCC7: client import
SCC1: copy as per transport request
The sales order … is currently being processed by user …
An inbound IDOC was failing due to the error [described in the title]. Some research resulted in the following results:
TR: SM12 displayed a list of locked elements in the system.
TR: SM04 displayed a list of logged in users in the local system.
TR: SM08 displayed a list of logged in users in all the app-servers [not just the current system].
Unfortunately in my case non of the mentioned transactions above helped me narrow down where the user was locking the system – in the end I’ve requested for the user to log back in and kill his session with a TR: /nex.
Usful SAP system tables.
| ADCP | Person/Address assignment (central address administration) |
| ADIRACCESS | Table to store keys for TADIR objects |
| ADR2 | Telephone numbers (central address admin.) |
| ADRP | Persons (central address administration) |
| APQD | DATA DEFINITION Queue |
| APQI | Queue info definition |
| D010SINF | ABAP- Information about ABAP program source code |
| E071 | Change and Transport System- Object Entries of Requests/Tasks |
| E07T | Change and Transport System- Short Texts for Requests/Tasks |
| ENLFDIR | Additional Attributes for Function Modules |
| INDX | System table INDX |
| NAST | Message Status |
| STXH | STXD SAPscript text file header |
| T005 | Countries |
| T005S | Taxes- Region (Province) Key |
| T005U | Taxes- Region Key- Texts |
| T006 | Units of Measurement |
| T015M | Names of the months |
| T247 | Month name and short text |
| T777A | Building Addresses |
| TADIR | Directory of Repository Objects |
| TBTCO | Job status overview table |
| TBTCP | Batch job step overview |
| TFDIR | Function Module |
| TFTIT | Function Module Short Text |
| TSP03L | Spool- Long device names |
| TSTC | SAP Transaction Codes |
| TSTCT | Transaction Code Texts |
| TUTYP | User Types in Current Price List in SAP System |
| TUZUS | Special versions |
| TVARV | Table of variables in selection criteria |
| TVDIR | View Directory |
| US930 | Data Relevant to Measurement for User Master Record |
| USR01 | User master record (runtime data) |
| USR02 | Logon data |
| USR04 | User master authorizations |
| USR06 | Additional Data per User |
| USR14 | Surchargeable Language Versions per User |
| USR21 | Assign user name address key |
| ARCH_OBJ | Objects for archiving and reorganization |
| BTCUED | Description of user event IDs for background processing |
| BTXSUPB | BSI- Upgrade-Information |
| CCCFLOW | Client Copy Control Flow |
| DBSTATC | DB Optimizer Control (Statistics Creation) |
| DEVACCESS | Table for development users |
| DEVL | OBSOLETE- Do not use (See TCETRAL) |
| E070 | Change and Transport System- Header of Requests/Tasks |
| E070L | CTS- Index for Assigning Numbers to Requests/Tasks |
| INSTVERS | Documentation for installation Status and History |
| PAT03 | Patch Directory |
| SDBAC | DBA Action Table |
| T100 | Messages |
| TAPLT | Program Application Long Texts |
| TASYS | OBSOLETE- Do not use, see TCEDELI |
| TDEVC | Development Classes |
| TEMSE | Temp Sequential table. |
| TLOCK | Change and Transport System- Lock Table |
| TNAPR | Processing programs for output. Can be very handy to find the print program for a SAPScript. |
| TNAST | Printed output control table |
| TPFET | Table of profile parameters |
| TPFHT | Profile header, administration data for profiles in DB |
| TPROT | Table contains all DD tables to be logged |
| TRBAT | Communication Table for Transport Control |
| TRDIRT | Title texts for programs in TRDIR |
| TRESN | Table of Naming Conventions in ABAP Workbench |
| TRJOB | Job ID for Coordinating Batch-ABAP/UNIX for Transports |
| TSP03C | Spool- Device Description Extension |
| TST03 | TemSe data |
| TSYST | OBSOLETE- Do not use (see TCESYST) |
| TWSYS | OBSOLETE- Do not use (See TCETRAL) |
| USOBT | Relation transaction – authorization object |
| USR03 | User address data |
| USR05 | User Master Parameter ID |
| USR12 | User master authorization values |
| USR40 | Table for illegal passwords |
| USR41 | User master- Additional data |
| UST04 | User masters |
| VARIT | Variant texts |
| VARID | Variant directory |
| D010TAB | Table for Use Report—Tables |
| DD02L | SAP tables |
| DD02T | R/3 DD- SAP table texts |
| DD03L | Table Fields |
| DD03T | DD- Texts for fields (language dependent) |
| EDIDC | IDOC Control Records |
| EDIDOT | Short description of IDoc types |
| EDID2 | IDOC segments (version 3.1) |
| EDID4 | IDOC segments (version 4.6) |
| EDSEA | EDI- Table of all segments of current release |
| VRSX2 | Central Table for Version Management (Report Source) |
| TSE05 | Can add parameters to the INSERT COMMAND (IC). Then, when you insert command, your info appears in the editor. Useful for comment blocks, common section of code, etc. |
| CDPOS | Change document items |
| CDHDR | Change document header |
| T529A | governs the foreground sequence of infotypes the system will use to prompt the user during online and batch processing. You will have to code your BDC to follow that sequence of creating infotypes. |
| T588Z | governs the dynamic event processing that will only take place during online user inputs. For BDC’s you will have to create separate BDC’s to handle any infotypes that are inserted dynamically by this table. |
| T588M | Infotype Screen Control |
Before Jack, before Chuck, and before time there was SAP.
The top 40 sap facts:
40) SAP is so efficient in creating software, there is actually only one developer writing code, all others are architects and managers.
39) What Yoda really meant to say about the force: Fear leads to anger. Anger leads to hate. Hate leads to ABAP.
38) The song “Killing me softly” was originally written by a SAP customer
37) The matrix runs SAP
36) When SAP NetWeaver was released, there was a disturbance in the Force
35) SAP is so secure that condoms are made from it
34) SAP can divide by zero.
33) By reading the source code of transaction SE38 you will temporarily be granted invisibility [SE38 starts up the editor]
32) SAP made Bill Gates retire. When asked why, SAP answered “Because we can”
31) SAP: It’s not just a job; it’s a wardrobe.
30) SAP stand for SLOW AND PAINFUL
29) Chuck Norris uses SAP to keep track of his death count
28) Not 42, but SAP is the answer to life, the universe, and everything.
27) Oracle still hides the fact that FUSION stands for: Finally use SAP in our network
26) The European Union has decided that by 2008, ABAP will be the only offical language used in parliament
25) If you post a question in the SDN ABAP forum, Rich Heilman already has the answer typed in and is just waiting for you to
press the “Post Message” button.
24) SAP only made its software so complicated because this way they were able to lay the foundation for the vast SDN community that would soon replace all SAP developers. As SDN points are easier to give away than monetary salary, the company’s increase in profitability is expected to crush all existing stock software, making place for SAP to installed in there, which would increase sales again … all in order with the SDN program (SAP Dies Never).
23) GOD runs SAP
22) It’s a little known fact that if you are on SAP’s network you will never get a “server not responding” or 404 page not found error… nobody is too busy to not talk to SAP.
21) His Holyness Pope Benedict XVI is an SAP certified ABAP programmer
20) The Klingon Empire runs SAP
19) SAP NetWeaver doesn’t adhere to the J2EE specification, the J2EE specification adheres to the SAP NetWeaver specification
18) All SAP consultants have a black belt in Karate
17) SAP invented the internet
16) SAP stands for Suffer After Purchase
15) The strongest and unbreakable argument in any architectural discussion is: “It was done this way in ABAP”
14) SAP stands for Start Applying Patches
13) Your SAP is not connected to the internet. The internet is connected to your SAP.
12) The real reason behind Pluto’s recent demotion from planet status: incomplete plant configuration in NASA’s SAP system.
11) It is rumored that Michael Corleone, “The godfather” used to work as a consultant in SAP.
10) The ultimate survival strategy if we ever find intelligent life in the galaxy is to SAP them right away …
9) Spiderman is powered by NetWeaver.
8) Julius Ceaser, Alexander the Great and Genghis Khan ran SAP. Their successors didn’t.
7) Sony Advanced Playstation
6) SAP next releases will come with a lifetime supply of Prozac
5) asap is actually an abbreviation for “in A SAP way”
4) Leonardo da Vinci was SAP Certified!!!
3) Whenever a new bug is found in SAP someone gets a hickup.
2) Every kid had his/her heroes…Boys had Superman, Girls had Lara Croft…And young Abapers…they had Rich Heilman.
1) On the first day God created SAP
…… That’s all folks ……
Connect to SAP through Java
This example will focus on exploring the ability to connect to an SAP application through the use of a remote Java client. The internal SAP arcitecture is designed in such a way that it does not matter if you connect through C, perl, .NET or Java the results will always be the same – A Function Module will take as in put particular information and will return accordingly resulting data.
This example will cover two main stages, first I will discuss the creation of the actual ABAP function following which I will explain the required libraries needed to connect to that function and retrieve the desired information. To make things simple I will build on top of the previous example.
Lets begin by creating a Function Module that could be accessed remotely by a client.
To create a new function one must access the Function Builder: Initial Screen [SE37] display.
Every function must belong to a particular function group.
A Function group is a collection of functions with similar data associations.
A new function group can be created by executing the ‘GoTo – Function groups – Create Function group‘ operation. For this example let’s create a new function group called ‘ztest‘. Once created we are ready to create a new Function Module, lets call it Z_REMOTE_FUNCTIONS_01. Once created add a new Export parameter with the following attributes:
| Parameter Name: | USER |
| Tap spec: | TYPE |
| Associated Type: | STRING |
| Pass Value: | Checked |
| Short text: | List of users. |
The completed attributes should generate the following line of source code:
FUNCTION Z_REMOTE_FUNCTIONS1. *"---------------------------------------------------------------------- *"*"Local interface: *" EXPORTING *" VALUE(USERS) TYPE STRING *"----------------------------------------------------------------------
In essence we created a string variable that will be returned upon the completion of the function. Our objective at this point is to gather informatoin from the USR02 table just like in the previous tutorial and package that up in to a return parameter.
*" Get reference to the user table. " TABLES: USR02. *" Initialize the return string. " USERS = '<users>'.* Grab information from the USR02 table. SELECT * FROM USR02. *" Use the CONCATENATE operation to append information to the return string. " CONCATENATE USERS '<user>' into USERS SEPARATED BY SPACE. CONCATENATE USERS '<name>' USR02-BNAME '</name>' into USERS SEPARATED BY SPACE. CONCATENATE USERS '<logdate>' USR02-TRDAT '</logdate>' into USERS SEPARATED BY SPACE. CONCATENATE USERS '</user>' into USERS SEPARATED BY SPACE. ENDSELECT.CONCATENATE USERS '</users>' into USERS SEPARATED BY SPACE.
Before proceeding to developing a Java client application ensure to switch off the Processing Type attribute to Remote-enabled module. This will ensure that it can be accessed by remote users.
Now lets turn our attention to setting up a Java client application.
Before we can write a single line of code we need to set up our environment so that our Java application can safely connect to an SAP engine.
To do that we will use JCo [Java Connector] that can be downloaded from the SAP Support Portal. Typically the file will be provided in a ‘.sar’ format. This is a compressed package that you can unpack using the SAPCAR application.
In addition to that you will need to install an RFC library, more information on how to accomplish this task can be found in notes:
| 413708: | RFC library that is current at this time. |
| 336693: | Replacing the librfc32.dll on a Win 32 Platform. |
After you download the JCo unzip it and locate the docsjcointro.html file which will guide you further in the Installation section.
After you complete the installation we are ready to start coding.
Create a new Java class called FunctionCaller.java.
import com.sap.mw.jco.*;
public class FunctionCaller{
public static void main(String[] args){
JCO.Client client = null;
try{
// Print the version of the underlying JCO library
System.out.println("nnVersion of the JCO-library:n" +
"---------------------------n" + JCO.getMiddlewareVersion());
// Create a client connection.
client = JCO.createClient("000",
"username",
"password",
"EN",
"hostname",
"00");
// Open the connection.
client.connect();
// Create an empty input/outpu parameter list.
JCO.ParameterList input = JCO.createParameterList();
JCO.ParameterList output = JCO.createParameterList();
// Specify the parameters types the function will be returning.
output.addInfo("USERS", JCO.TYPE_STRING,255);
// Call the function.
client.execute("Z_REMOTE_FUNCTIONS1", input, output);
// Print the result
System.out.println("The function 'STFC_CONNECTION' returned these parameters:n" +
"-----------------------------------------------------------------");
for (int i = 0; i < output.getFieldCount(); i++) {
System.out.println("Name: " + output.getName(i) + " Value: "
+ output.getString(i));
}
// Close the connection.
client.disconnect();
} catch (Exception e){
System.out.println("Caught an exception: n" + e);
if ( client !=null )
client.disconnect();
}
}
}
The contents of the above class will establish a connection with the SAP server and execute the created function retrieving EXPORT variable USERS.
Note: Make sure you compile your code with the appropriate classpath including the sapjco.jar container.
Retrieving user data [ABAP]
In this example we will explore attempts to gather information from SAP database tables. We aim to collect user information and display it on the screen using SELECT statements and internal TABLE variables.
For the purposes of this example we will be collecting information from the table USR02.
In order to access that information the program must explicitly reference the desired tables at the header of the file.
REPORT Z_USERS.
* Import the USR02 table in to the program.
TABLES: USR02.
Next we want to create a internal table for gathering information from the database. We will create a local variable table ‘USERS’ with two attributes. All variables used within the ABAP/4 program must be declared with DATA statements.
DATA
<name> Name of the variable
TYPE or LIKE Indicates the variable type.
VALUE Initial value of the variable.
DECIMAL Can only be used with appropriate types. Specifies the number of decimal places in the number.
* Define USERS internal table.
DATA: BEGIN OF USERS OCCURS 100,
NAME LIKE USR02-BNAME,
DATE LIKE USR02-TRDAT,
END OF USERS.
BEGIN OF USERS OCCURS 100: Specifies the name of the variable table ‘USERS’ and states that the table will contain a 100 records.
The two attributes that the table will contain are NAME and DATE with the same characteristics as BNAME and TRDAT attributes found in the USR02 table. The BNAME attribute stores the name of the user while the TRDAT attribute stores when the user previously logged in.
END OF USERS is a closing statement for the BEGIN statement.
The next step will be to use a SELECT statement to gather information from the USR02 table and populate our local USERS table.
* Select information from the USR02 table.
SELECT * FROM USR02.
CLEAR USERS.
* Copy over the information.
USERS-NAME = USR02-BNAME.
USERS-DATE = USR02-TRDAT.
APPEND USERS.
ENDSELECT.
The SELECT statement acts like a ‘loop’ if you will. Record by record the information will be gathered up from the USR02 table and transfered in to the USERS table. After going through each record the data is added to the USERS table using the APPEND statement.
Now that we gathered some information about the users that reside in the system lets display that info.
First lets find out how many users there are in total. To do that we will use the DESCRIBE statement that will return an attribute LENGTH of all the fields in the USER table.
* How many users were retrieved.
DESCRIBE TABLE USERS LINES LENGTH.
* Output the information on the screen.
WRITE: / 'There are: ', LENGTH, 'USERS'.
The final step in our program will include the displayed of collected user information.
Using a LOOP statement we will go through each element in the USERS table and output the information on the screen.
LOOP AT USERS.
WRITE: / USERS-NAME, USERS-DATE.
ENDLOOP.
Notice that the LOOP statement terminates with a corresponding ENDLOOP statement.
And this completes our glimpse of data gathering in SAP.