0 ratings0% found this document useful (0 votes) 114 views44 pagesABAP Objects - Basics Guided Tutorial
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Introduction
This exercise is a tutorial or guided tour through the fundamental language elements of ABAP
Objects and the usage of the respective ABAP Workbench tools. The tutorial is designed for
developers who have had little or no experience with ABAP and ABAP Objects until now.
The following class diagram shows the scope of the exercise
Generation of UML Class Diag'
@) SB) A) |) By comico
“lnterfaco>>
“oF STATUS, XX
ZEL_VENICLE x
D
feraxsreco
espero
[> CONSTRUCTOR)
-SeEED UF()
RECENT
ZcL_TRUCK ¥K
(Goat) Rae
|: Ze_STATUS SHOW)
[IFSTATIS SHO) [-constaucToR()
ls coRsTeUcTOR() [psPeED UPL)
fr ecevers> DAMAGED)
ZCL_APPLICATION XX
abstract)
Esra
ic L Z I To)
Ready Nodes[— 6 Links| —a)Size 9804009)
[nano eeaeaa [ws [|Z
(After finishing the exercise, you should be able to display this diagram for your own classes)
THE BEST-RUN BUSINESSES RUN SAP’ ewExercise 1, Classes and Objects
(Solution in Package Z ABAP_OBJECTS INTRODUCTION A)
Create a vehicle class
Create a class ZCL_VEHICLE_XX (where XX is your group number).
«= The class should have the protected instance attributes SPEED and MAX_SPEED for its speed and maximum
speed, and the public methods SPEED_UP, STOP, and SHOW. Furthermore there should be a private attribute that
contains a running number for an object ID.
= SPEED_UP should have an IMPORTING parameter STEP. The method should increase the speed by STEP, but not
allow it fo exceed the maximum speed.
= STOP should reset the speed to zero.
= WRITE should display @ message containing the speed and the maximum speed.
Solution
Logon to the system and open the Object Navigator of the ABAP Workbench (Transaction SE8O, enter /nSE80 in the
‘command field of the system task bar).
» Select Local Objects in order to work in a test package that is not transported to other systems,
=
[Program
iHFunction Group
Hit Enter.
3 THE BEST-RUN BUSINESSES RUN SAP’ ew» Right Click the name of the local package and navigate to the creation of a class (where XX is your group number)
Local Objects
[ABAP_OO_YX
ere
Is
>)
ObjectName
Development Coordination
Change Program
Display >| Function Group
Copy. Web Dynpro .
Delete Dictionary Object .
Cheek 5
Display Object Directory Entry Cea {ntertace
‘White Transport Entry BSP Library .
Where Used List Enhancement .
(Other Functions , | Business Engineering .
Form object .
Test Object .
‘other (1) .
other (2) ,
Fill the pop-up as follows ZCL_VEHICLE_XX (where XX is your group number) and select Save.
Class 2CL_VEHICLE_XX
Description Vehicle class
Instantiation Public
@ Usual ABAP Class
Okxeeption Cla:
Cwith Message Class
OPersistent class
O'Test Class (ABAP Unit)
(Don't forget to uncheck Final)
THE BEST-RUN BUSINESSES RUN SAP’ ew© Acknowledge the following window without changes (select either Save or Local Object).
[= Create Object Directory Enty a
‘2CL_VEHICLE_xx
Peage ne
Person Responsible ABAP 00 XX
Original Systern
Original language
Created On.
The same holds for all other development objects during this exercise.
5 Now you enter the Class Builder
Class Builder: Change Class ZCL_VEHICLE_XX
cies res [ZEL_YEMICEE pronto nace
Loss obed a
[S212 ra) ett)
(106) <1]
[ a0 Geo EB a0 [RB | 7
Here you can edit the class either in Form-Based mode (default) or in Source Code-Based mode. Use the
respective button to toggle between the modes.
1 Switch to Source Code-Based mode SB SOUS COSEEEEEE no change mode land replace the
existing template with the following code (where XX is your group number).
CLASS 2¢1_vehicle xx DEFINITION PUBLIC CREATE PUBLIC.
PUBLIC SECTION.
METHODS constructor.
METHODS speed_up
IMPORTING
5 THE BEST-RUN BUSINESSES RUN SAP’ ewPROTECTED SECTION.
DATA: speed vee i,
max_speed TYFE i VALUE 50.
PRIVA’ TON.
DATA id TYPE i.
CLASS-DATA object_count TYPE
ENDCLASS.
LASS zel_vehicle xx IMPLEMENTATION.
METHOD Constructor.
object_count = object_count + 1.
id = object_count
ENDMETHOD.
METHOD show.
DATA mag TYPE string.
meg - ‘Vehicle * ee (id )1 ae
*, Speed =~ 6 If speed }1 66
*} Max-Speed = > && I{ max_speed } 1.
ESSAGE mag TYPE 'I'.
speed = speed + step.
IF speed > max_speed.
speed = max_speed.
ENDIF.
Check, 4) save EI and Activate _* the class (acknowledge all entries of the activation pop-up ).
‘Switch back to Form-Based mode [=a Fomm8ased | 4 say around in that mode by double clicking the class
components
THE BEST-RUN BUSINESSES RUN SAP™ ewClass Builder: Change CI
[Loa cbeds 8)
i 1S) ae
ns 0 a2 [8 | |Z
Pretty Printer
Ty. [Parameter (Type spec.
‘STEP TYPEI
Method _[SPEEI
TG] method speed_up.
speed = speed + step.
if speed > max_speed.
speed = max_speed.
endif.
endnethod.
Create an application class
Create a class ZCL_APPLICATION_XX (where XX is your group number),
« This class should use your vehicle class.
«= Itshould have simply one static method START that creates and uses objects of ZCL_VEHICLE_XX.
Solution
* Create the class in the object navigator, where you can directly right click Classes now
THE BEST-RUN BUSINESSES RUN SAIEy ele]
2 Fill the pop-up as follows (where XX is your group number).
Class ‘2CL_APPLICATION_XX
Description Application class,
Instantiation ‘Abstract
© Implement the class as follows:
CLASS 2cl_application_zx DEFINITION PUBLIC ABSTRACT FINAL CREATE PUBLIC.
PUBLIC SECTION.
CLASS-METHODS start.
PROTECTED SECTION.
BRIVATE SECTION.
ENDCLASS.
CLASS ZCL_APPLICATION_XX IMPLEMENTATION.
METHOD Start.
DATA vehicle TYPE REF TO zcl_vehicle xx.
DATA vehicle tab LIKE TABLE OF vehicle.
DATA tabindex TYPE i.
Do 10 TIMES.
CREATE OBJECT vehicle.
APPEND vehicle TO vehicle tab.
ENDDO.
LOOP AT vehicle tab INTO vehicle.
tabindex = sy-tabix * 10.
vehicle->speed_up( tabindex ).
vehicle->show().
ENDLOOP.
ENDMETHOD.
ENDCLASS.
8 THE BEST-RUN BUSINESSES RUN SAP™ ewcheck, [4] save EB and Activate [the class (acknowledge ll entries ofthe activation pop-up).
«Select [& (F8) in the Class Builder and execute method START
QZCL_APPLICATION 1x
Attributes
Lc Nethods
starr g
Now you can see the Ids and speed of the objects created
[= information
© To examine further, navigate to the source code of method START "and create a breakpoint at an appropriate
position. To add a breakpoint at a certain line, double-click in the left margin on the line that you want a breakpoint. A
little © should appear in the margin on that line. Similarly this is the same way you remove a breakpoint.
Metros Est _Goto_Uuliest
Ae ®
METHOD stare.
yep. ma marae
27 abit aerwar
rss _00.5a (zee) ° APPEND vehiele 70 vehicle tab.
[Eves 1c emi
$18) Leal) | 5 Eotr ir ventete cab avo venice.
37 unas es
eI vehicle->epeed up| cabindex ).
[Seope WETHOD siaMO SABA (tn Cok 20
Fan 0)
l a0 c) 800 Fa] watn022 [ins | [7
Test the method again and play around with the ABAP Debugger.
8 THE BEST-RUN BUSINESSES RUN SAP’ ewExercise 2, Inheritance
(Solution in Package Z ABAP_OBJECTS INTRODUCTION B)
Create a truck subclass
Create a subclass ZCL_TRUCK_XX (where XX Is your group number)
‘The class should have an instance constructor that sets the maximal speed to 100
« Itshould redefine the method SHOW to produce some specific output.
Solution
Create the class in the object navigator as before, but select Create inheritance ((4) this time in order to enter a
‘Superciass
[= Create Class
Class Z2CL_TRUCK_WX
Superciass ZCL_VEHICLE_Xx
Description Truck class
Instantiation Public
@ Usual ABAP Class
OBxception Cla:
Cowith Message Class
OPersistent cla
(Test Class (ABAP Unit)
and Activate
2 Enter the truck's own constructor in the Form-based mode (type itor select Create constructor =! Cansiruetor |
double click it and implement it as follows:
METHOD constructor
super->constru
maz_epeed = 100.
ENDMETHOD.
and Activate |
10 THE BEST-RUN BUSINESSES RUN SAP’ ew+ Select method SHOW in the Form-based mode and redefine it by selecting [R@ll. Replace the implementation as
follows
MsT#0D show.
DATA mag g
meg = “Truck ° ae
ae I{ speed }1 a6
> && I{ max_speed }.
« save Band activate [1
Cheok out the syntax in te Source code-based mode
Create a ship subclass
Create a subclass ZCL_SHIP_XX (where XX is your group number).
= The class should have an instance constructor that sets the maximal speed to 30 and that has an import parameter
to set an additional read-only attribute to the ship's name.
« It should redefine the method SHOW to produce some specific output (including the ship's name).
Solution
+ Create the subelass ZCL_SHIP_XX in the object navigator as you did before for the truck class (where XX is your
group number)..
‘Add a new public instance attribute NAME of type STRING either in Form-based mode or in Source code-based
mode.
Clas rtartaca (20t_sHIP.98 |tmlomentedinaciv (vised)
Propertes | ineroces | lends MEIN wenoos | everts | Types | Aleses
Ce) xale
ribute (Lev sity [Readoniy [Typing DDeseripton nat value
[<2ch_VENTOLE_@@> o
SPEED instance Abt Protected ype
SPEED, instance atibute Protected Di ype
i instance Aibuie Public Dye
» Insert the ship's own construetor as you did for the truck class.
Create an importing parameter for the constructor either by selecting Parameter in Form-based mode
Class Interface 2CL_SHIP_XX Implemented
Method parameters
ype STRING
or by adding it in Source code-based mode:
ETHODS cons
IMPORTING
name TYPE string.
WV THE BEST-RUN BUSINESSES RUN SAP™ ew
uctor«Implement the constructor as follows:
12
METHOD CONSTRUCTOR.
super->constructor( ).
max_speed
ma-Sname
THE BEST-RUN BUSINESSES RUN SAP~ ewRedefine method SHOW as follows:
METHOD show.
DATA msg TY:
save & and activate 1
Check out the syntax in the Source code-based mode,
Adjust the application class
The code of the START method should demonstrate the usage of the subclasses now.
«= Declare extra reference variables TRUCK and SHIP for the new classes.
= You can delete the code that creates objects for VEHICLE. Instead, create one instance of each of your new
subclasses and place the corresponding reference into VEHICLE_TAB.
«= Call the method SPEED_UP for beth classes using the respective subclass reference, and SHOW using a
superclass reference.
Solution
Replace the code of method START of ZCL_APPLICATION_XX with the following (where XX is your group number)
Ds
DATA: vehicle TYPE REF TO zcl_vehicle_xx,
vehicle_tal 1e,
suck TYPE
‘Titanic’.
ENDMETHO!
Note the polymorphic method call vehicle->show( )
2 Execute method START from the Class Builder again,Exercise 3, Interfaces
(Solution in Package Z ABAP_OBJECTS INTRODUCTION C)
Create a status interface
= Create an interface ZIF_STATUS_XX (where XX is your group number).
«= The interface should have one instance method SHOW.
Solution
"Create the interface in the object navigator as follows:
> CI ZCL_APPLICATION >
> CZcL_sHIP x
> (C2eL VEHICLE 5x
Interface 2IF_STATUS_xx
Description Status Interface
Cloniy moselea
2 Define one Method without parameters:
Interface ZIF_STATUS_XX
save | and Activate
4 THE BEST-RUN BUSINESSES RUN SAIImplement the interface in the superclass
Implement ZIF_STATUS_XX in ZCL_VEHIGLE_XX (where XX is your group number).
= Copy the implementation of the class method SHOW to the interface method SHOW.
= Delete class method SHOW
= Create an alias name SHOW for the interface method in order to keep the subclasses valid,
Solution
» Open ZCL_VEHICLE_XX and enter the interface either in Form-based mode
Class intertace ‘2CL_VEHICLE_3X Implemented s Actve
or in Source code-based made:
PUBLIC seCrLoN,
THTRRFACRS i f_al
2 Implement the interface method with the code from SHOW:
mersov if otatue mx-chow,
TATA mag TPR shring.
msg - “vehicle ~ a6 14 dd tl ae
‘Speed - > 46 [4 peed tl ae
T) MaxeSpecd — 48 [max speed JI
messace’ mag Five '1"
SENMET SOD
» Delete (IES) method SHOW.
« Create a public alias SHOW:
Class Interface: ‘2CL_VEHICLE_ XX Implemented J Active
ZIF_STATUS_Xx-GHOW @ suo Pubic
«Save Gl ang activate 1.
‘Check ZCL_TRUCK_XX and ZCL_SHIP_XX (where XX is yeur group number), They redefine the superclass
interface method SHOW via the alias SHOW now and there should be no errors,
15 THE
ST-RUN BUSINESSES RUN SACreate a new helicopter class that also implements the interface
Create anew class ZCL_HELICOPTER_XX (where XX Is your group number) that is not part of the
ZCL_VEHICLE_XX inheritance tree but that also implements STATUS.
Solution
Create class 2CL_HELICOPTER_XX (where XX is your group number) as follows:
INITION PUBLIC FINAL
cuass 201 TE PUBLIC
Licopter ex
PRIVATE SECTION.
ENDCLASS.
ENTATION.
DATA mag TYPE str:
msg = “ficlicopter, idle
MESSNER msg TYE IT!
> Save Band Activate E
‘Adjust the application class
‘The code of the START method should demonstrate the usage of the interface now.
= Declare a reference variable HEL! forthe class ZCL_HELICOPTER_XX following (where XX is your group number)
and create a corresponding abject.
= Replace the reference variable VEHICLE and the table VEHICLE_TAB-with an interface reference STATUS and an
internal table STATUS_TAB,
« Insert the reference variables for truck, ship and helicopter into the table STATUS_ TAB,
Solution
+ Replace the code of method START of ZCL_APPLICATION_XX with the following (where XX is your group number)
10 zcl_truck_xx,
10 zcl_ship xx,
70 2el_helicepter sx
PORTING name = 'Titanic',
APPEND
truck To
hip TO
heli To
truck->epeed
ship->spe
NDLOOP.
METHOD.
Note the polymorphic method call status->show{ }
Execute meted START from the Class Builder again.Exercise 4, Events
(Solution in Package Z_ABAP_OBJECTS_INTRODUCTION_D)
Define an eventin the ship class
Objects of ZCL_SHIP_XX (where XX is your group number} should raise an event i the speed becomes higher than
the maximal speed.
= Define an instance event DAMAGED in ZCL_SHIP_XX
«= Raise the event in method SPEED_UP
‘Solution
5 Open ZCL_SHIP_XX (where XX is your group number) in the Class Builder and define an instance event DAMAGED
either in Form-based mode:
Class Interface ZCL_BHIF_XH Implemented / Active
Instance Event
‘or in Source corle-hased made:
PIMETE SRCTTON.
svanus damaged,
> Redefine (Gl) method SEED_UP and implement tas folows:
METHOD 51
oped - speed | step.
TF speed > max_speed
max_speed ~ 7
D atop.
CNT damaged
iF
Define an event handler method in the helicopter class
‘The helicepter class should be able to handle the event DAMAGED of the ship class.
«= Define a public method RECEIVE as an event handler for event DAMAGED of ZCL_SHIP_XX in
ZCL_HELICOPTER_XX (where XX is your group number)
«= Implement the event handles in a vrayrthat is simply sends a message that uses the default event parameter
‘SENDER to address the name of the damaged ship .
7 THE BEST-RUN BUSINESSES RUN SA‘Solution
1 Open ZGL_HELICOPTER_XX (Where XX is your group number) in the class builder.
In Form-based mede, enter a new publit methed RECEIVE and select Detail view ( J) where you can define the
method as an Event handler;
Class Intertace (ZCL_HELICOPTER_XX Implemented s Actwe
‘ZCL_HELTCOPTER_XE
RECEIVE
event hanaler or
Classiinterface _[ZCL_SHIP_Xx
Event DAMAGED
|Omodeies
|DDEdtor tock
DActive
Created ty
Last changed by (Dein)
Last changed by (mp)
SENDER Imporin,
In Source code-based mace itis enough to type:
METHODS receive
FOR EVENT damaged OF 2cl_ship_xx.
IMPORTING sender.
18 THE
ST-RUN BUSINESSES RUN SA19
Implement methad RECEIVE as follows:
METHOD receive
DATA meg TYPE string.
mag = ‘Helicopter received call from
MESSAGE msg TYPE 'I'
ENDMETHOD.
se oender-oname
» save GU and activate [2
Adjust the application class
‘The code ofthe START method should register the instances of the helicopter class for the events of the ship class.
«= Use statement SET HANDLER to register the event handler.
= Call method SPEED_UP of the ship cbject in order to raise the event
Solution
Replace the code of method START of ZCL_APPLICATION_XX with the follawing {where XX is yaur group number}:
vo zu
TATE
pratus um,
ship xx,
[Be Topline
= ‘yitenic’,
status_tab,
70 #tatus_Lab|
elissreceive FOR AL. THSt
ENDMETEOD.
Execute method START from the Class Bulider again.
THE BEST-RUN BUSINESSES RUN SAP SAP AExercise 5, Exceptions
(Solution in Package Z_ABAP_OBJECTS_INTRODUCTION_E)
Define an exception class
Objects of ZCL_VEHICLE_XX should raise an exception ZCX_OVERHEATING_XX (where XX is your group number)
if the speed becomes higher than the maximal speed.
«= Define an exception ZGX_OVERHEATING_XX (where XX is your group number)
«= Raise the exception in method SPEED_UP.
‘Solution
5 Open ZCL_VEHICLE_XX (where 20X is your group number) in the Class Builder, place the cursor on method
SPEED_UP in Form-based mode and select the bution Exception.
> Mark Exception Classes and enter ZCX_OVERHEATING_XX (where XX is your graup number).
(| Exception Classes
oO
and select Yes and Save on the follawing pop-ups with respectively.
[ie Exception class does not exist a
Exception class 2Cx_OVERHEATING_Xx
does not exst
erent cee
[= Create Class ZCX_OVERHEATING_XX a
Class 203_OVERMEATING_1X
Superelass CK_STATIC_CHECK
Description Motor damage
Instanition (Public
(© Usual ABAP Class
@ Exception Class
Cviiin message class
CO Persistent cla
Test Class (ABAP Uni
20 THE BEST-RUN BUSINESSES RUN SA.« Double click the name of exception class, Activate it and return to the vehicle class.
5 Change the implementation if method SPEED_UP as follows (where XX is your group number):
ME!
D speed sp.
speed = speed + step.
TF speed > max_speed.
RAISE EXCEPTION TYPE zex_overheating xx.
NDIF
ENDMETHOD,
+ Save Gl and Activate
Adjust the application class
‘The code ofthe START mathod must handle the exception now.
= Use a TRY control structure ta handle the exception ZGX_OVERHEATING_XX (where XX is your group number)
= Call method SPEED_UP of the truck abject in order to raise the exception.
Solution
5 Check the syntax of method START of ZCL_APPLICATION_XX (where XX is your group number). Yau should get
the following warnings:
The extention ZCH_OVERHEATING_}0tis nesther caught noris it declared
inthe RAISING clause of"START.
The exception ZCX_OVERHEATING_}tis neither caught noris it declared
inthe RAISING cisuse of*START
The exception ZCX_OVERHEATING Ys neither caught noris it declared
inthe RAISING clause of START
2 Adjust the implementation of method START .as follows {where XX is your group number)
ob tart.
DATA: statue = TY! 10 aif _etatue_xx,
status_tab LIKE TABLE OF status,
truck TYPE REF 70 2cl_truck_xx,
ship TY?! 10 2clTship Ex,
heli TYP! 10 2cl_helicopter_xx
EATE OBJECT: teuek,
ship EXPORTING name = 'Titanic’,
heli.
APPEND! truck To status_tab,
ship To status_teb,
heli TO status_tab
HANDLER heli->receive FOR ALL INSTANCES
teuck->epeed_up( 30 ),
Ship-sspeed_ap( 10).
LOOP AT status tab INTO status,
status->showT }
DLOOE.
po § TIMEs
21 THE BEST-RUN BUSINESSES RUN SAnip-pepe|d_ up
ENDO,
DO 5 TIMES.
truck->speed_up| 30 }.
teuck=>show{ }.
ENDDO.
ed! TYPE 'T*,
No syntax wamings should oceur any more.
» Execute methed START from the Class Builder again.
Exercise 6, Unit Tests
(Solution in Package Z_ABAP_OBJECTS_INTRODUCTION_F)
Define a test class with a test method far the vehicle class
Class ZCL_VEHICLE_XX (where XX is your group number) should contain a test class that tests the SPEED_UP
method completely.
= Declare and implement a local test class TEST_VEHICLE in the wehicle-class.
Solution
1 Open ZCL_VEHICLE_XX (where XX is your group number) in the Class Builder an select the following:
ie
Glass Edit Goto Uuliwes Environment system Help
Sections
Class Buil
P
Proxy Ea
Back
icle mx
‘Documentation .
‘Translation
Object airectory entry
‘Application help
. 199 relevanttlocal Definitions, Pr
‘Test elements Local Test Classes,
presentat Me
crs.
‘ Class interface ‘2EL_VEHICLE_1
cle DEFINITION DEFERRE!
FINITION LOCAL FR
ENDS test_|
‘The second statement is the important one. It deciares the test class as friend of the global class in order to have
access of the vehicle's private components, The first statement is necessary for the ABAP Compiler. (select F1 to
learn more)
22
ey
THE BEST-RUN BUSINESSES RUN SANavigate back te the Class Builder's main screen and select Local Test Classes in the above menu, answerthe
pop-up with Yes. and implement your test ciass as follows (Where XX is your group number)
CLASS test_vehicle DEFINITION FOR TESTING
18K Li HARMLESS
PRIVATE SE
DATA vehicle TV? =
‘test_speed_up FOR TESTING,
setup,
teardown
CLASS teat_vehicle IMPLEMENTATION,
METHOD setup.
CRATE OBJECT vehicle
snwnerno:
METHOD teat speed up
TR
cle Depeed up ( 50).
ol_abap_unit agsert->aszert_equala(
RXPORTTNG
exp - 50
act = vehicle oopeed
meq = 'Spond mol, as expoxled!
Ievel = i eine
Liesl)
cANGH zon ov
cl_abapy
ExvouTive
mag - 'No exception expected"
Invel — 1_aunil_conelanieseri tical }
sNbURE.
TRY.
edup( 1000 D6
ihazserk-staild
PORTING
meg 'Rxcephian expected!
z0H_ove:
tupit_conetante=seritical }
ting xx.
edown.
vebicle.
« Navigate back to the Class Builder's main screen. Save © and Activate
Carry out the test method by
Class > Unit Test in the Class B.
or
‘Test > Unit Test from the context menu of the class in the Repository Browser
‘The result should be:Use the ABAP Unit Browser
Examine the possibilities of the ABAP Unit Browser embedded in the Object Navigator
‘Solution
» Select Utilities - Settings in the Object Navigator and additionally select the ABAP Unit Test Browser under
Workbench (General):
[Ee User-Specitc Setiings &
2 Select the ABAP Unit Browser
———
5 Select Glass Pool, enter ZGL_VEHIGLE_XX (where 2X is your group number), and carry out the test with measuring
the test coverage:
24 THEVEHICLE seal]
‘Expand subtree
suntres
Object Dieeetory Entry
| Affer successful execution you can navigste through the results to view the test coverage:
25 THE
'ST-RUN BUSINESSES RUN SAP’ eryCLAS Z0L_ VEHICLE 208
00,00 WET: CONSTRUCTOR
1000 WET SPEEDUP
oo Men sro
“ZCL_VENICLE 0
|ZoL_VENICLE
\2EL_VEHICLE 3
1200 MET! DF_STATUSJeIGHOW _ZCL_VEMICLE po
ef
2] wy 800 a wean | mek | 6 |
ABAP Unit: Statement Coverage
Prograe 2c VEHICLE
7] G_RETHOD opoed up
130. 800 68 wonns072 [ws | [77
28 THE BEST-RUN BUSIExercise 7, Service Enablement
(Solution in Package ZABAP_OO SERVICEENABLEMENT
Expose Method As Web Service (Inside-Out Approach)
Inthis exercise,
‘© You will create a RFC-enabled Function Module to invoke the
IF_DEMO_CR_CAR_RENTL_SERVICE~MAKE_RESERVATION method from Class
cL_DEMO_CR_CAR_RENTAL_SERVICE
Copy existing RFC-enabled Function Module into your Function Group
Expose the RFC-enabled Function Modules in the Function Group as a Web Service
Configure/Test the web service using SOAManager and Web Service Navigator
Optionally, debug using an external breakpoint
Poperes | eroces Friends Aibutes Events| Types
© Parameter 9_Esooton [7a [oj alieate of | iter
menos Lert istity_Nehod ye [Destston
1F_ben_R_CAR_RENTL_BERVIGE“CREATE_GLBTORER instance Fthod ubtie ate Cusumer
{F_OEnO_CA_CAR_RENTL_SERVICE-GET_CARS_6Y_CATEGORY Instance fetnod puoite ‘Seton Cars ty Cateaor
'TF_Ben0_GR_CAR_RENTL_SERVICE-OET_CUSTOMER_Y_10 instance netnod puise ‘et Curomerty
1F_DEnO_GR_CAR_RENTL_GERVICE-DET_CUSTONERS_Y_NAME instence fethod uote (eteustomersbynane
TF _DENO_CR_CAR_RENTL_SERVIOE-GET_REBERVATIONG_Y_CUSTLID Instance Retned Puonic ‘Set Roseraton ty Cusoreri6
TEND CROAR_RENTL-SERVICE-TARE RESERVATION) Instance fsthod Punic ‘rate Rosonaton
eT senvice atic Rethod Punic (at Singin for Seek
(CLASS. coneTRUCTOR atic Wethod Public | 38 State Constuebr
Solution
Logon to the system and open the Object Navigator of the ABAP Workbench (Transaction SE80, enter /nSE80 in the
‘command field of the system task bar)
Select Local Objects in order to work in a test package that is not transported to other systems.
27 THE BEST-RUN BUSINESSES RUN SAP’ ew‘Create a Function Group
* Right Click the name of the local package and navigate to the creation of a Function Group.
+ Enter ZFG_XX (where XX is your ber) and short text. Click Save
Soe [= crest Funcon Grows
ai
(ook ta Funeon oroup ae
shanted Funaton Oraup for ABAP 09 - rep
eonResponemie BHP A084
Em
= Acknowledge the following window without changes (select either Save or Local Object)
(Devine gine)
\ (Create the function module.
* Expand the Function Groups Folder. Right click on the fimetion group. ZFG_XX, sand choose
Tumetion Module
[Desenpton
~ Cl Funenon oroupe,
e
Bisping + Subroutine
* Enter ¢CustomerReserveCar_XX (where XX is your group number) and short text. Cliek Save.
[Greate Funan weatle
Funeton Mediule 2CustonerReservecar_1
Functan group FX
Shot tet “Reserve GartorCustomed
io Save |
+ You ean disregard the following informational message whenever it may appear
F=f
2 THE BEST-RUN BUSINESSES RUN SA.Define the function module interface by entering its parameters
‘© Provide the import parameters for the function module under Import tab
Parameter Name | Typing Associated Type Pass Value
CUSTOMERID _| TYPE DEMO_cR_cusToMER_ID |
CATEGORY TYPE DEMO_CR_CATEGORY a
STARTDATE TYPE DEMO_CR_DATE FROM |
ENDDATE TYPE DEMO_CR_DATE_TO a
Function module ZCUSTONERRESERVEGA Inactive Revised)
attributes Export | Changing | Tables | Exceptions Source code
> [tale et
Parameter Name [Typing [Associated Type (Default value|Optional_[Pass Value Shor tex
CCUSTOMER_10 TYPE EMO_CR_CUSTOMER_1O Oo (CustomerID
cATEsoRY TYPE DEWO_cR_CATEGORY o (Cat Category
STARTOATE TYPE DENO_CR_DATE_FRON O | @ Statpate
ENDDATE TYPE EMO_CR_DATE_TO oO BH End Date
o oO
‘© Provide the export parameters for the function module under Export tab
Pass
Parameter Name | Typing Associated Type Value
RESERVATIONS | TYPE DEMO CR RESERVATIONS 1T| @
RETURN TYPE BAPL MSG a
Function module ZCUSTOMERRESERVECAR_XX Active
Attributes: Impor Changing Tables Exceptions Source code
Parameter Name i ‘Associated Type Pass Val_|Short text
RESERVATIONS YPE DENO_CR_RESERVATIONS_1T | [| [Table Type for Reservation
RETURN YPE BAPI_NEE [Message Tet
Oo
* Please mark “Remote-enabled Module” radio button under Attributes tab.
emer© Complete the source code for your function module under Source Code tab.
mtn TOMERESERECAR Kae
pot | Gat _ cranny Tame _ Ext
You can toggle between Display and Change mode
using the [A icon.
© Add the ABAP source code
DATAt lr eervice TYPE REF TO if demo er car 3
lovexception TYPE REF TO Gz_root,
l_Gustomer TYFE demo_cr_scugtomer,
llreservation TYPE demo_cr_ereservation.
entl_service,
lr_service = cl_demo_cr_car_rental_service=>get_service( ).
TRY.
Lr_service->make_reservation(
EXPORTING
i_customer_id
seategory category’
iodate from = startdate
iidateto = enddate ).
CATCH cx_demo_Gr_no_customer cx_demo_cr_lock cx_demo_cr_reservation INTO lo_excep
tion.
return = lo_exception->get_
EXIT.
CATCH Gx_root INTO lo_exception.
return = lo_exception-oget_text( ).
customer_id
ext( ).
EW
l_customer = 1r_eervice->get_customer_by_id( customer_id ).
ALL reservations for
ly service >get_reservations by cust id( customer id ).
rds not ma tad Bt;
* Method retu
reservations
* De.
DELETE reservations WHERE date
* We still may have the situatioi
e times
CASE lines( reservations ).
WHEN 0.
return = “Unable to confirm reeervation ~ Contact Help Desk’.
WHEN 1.
READ TABLE reservations INTO 1_reservation INDEX 1.
return = "Reservation && 1_reservation-
reservation id && © Booked for ° Ek 1 customer-nane.
WHEN OTHERS
sort reservations by reservation_id ascending.
return = “Multipe reservation exist for © «a 1_customer-
name 4& ° in the selected time period’.
ENDCASE.
+ check, 4] save Bl and Activate [E the Funetion Module
30 THE BEST-RUN BUSINESSES RUN SAP~ ewCopy 3 additional Function Modules from a different package into your Function Group
# Navigate to Package - ZABAP_OO_SERVICEENABLEMENT click Display 2]
Local Objects al Package
ela] Tn 7)
Puro a if 15 [A] [S/O] | (ew
Function Group
Class / Interface [Description] fonject Name Description
tems ores oy | |? SI ZABAP_00_SERVICEENABLENENT Senco Enat
Jj Dynpro Camp,
BSP Application (2 Function Groups
BSP Extension
Inactive Objects ‘Function Gro
Local Objects: dules
D Clincudes
© Expand the Funetion Groups folder to display the Funetion Modules
15 [ 1 )\[% [3] (es [2] | [ea
Name Description
‘© CU ZABAP_OO_SERVICEENABLENENT Benice Enablement of ABAP OO Exercises
Function Groups
> CO ZA00%K TestFMs
‘© i Function Modules
‘ZCUSTOMERCREATE_YX Create Customer
‘ZCUSTOMERFINDBYNAME_¥ Find Customer by Name
ZCUSTOMERGETRESERVATIONS XX Get List of Customer Reservations
ZCUSTOMERRESERVECAR_XX Reserve Car for Customer
P includes:
© Right-click on the ZCUSTOMERCREATE_XX Function Module and Select Copy
OnjectName [Description
© (i) ZABaP_00_SERVICEENABLEMENT ‘ence Enablement ofABAP OO Brercises
© Function Groups
= I Z000K% Test Fs
> GI Function Modules
ZCUSTOMERFINDBYNAME_ XX Greate >
‘ZCUSTOMERGETRESERVATIONS Change jservations
‘ICUSTOMERRESERVECAR_XX aes , er
P Cincludes eee
check
Activate
Test ,
Rename.* Enter the Following
© To Function Module ZCUSTOMERCREATE_99 (replace 99 with your group number)
© Funetion Group ZFG_99 (replace 99 with your group number)
© Select Copy
[= Copy Function Module
2CUSTOMERCREATE_Xx
‘ZOUSTOMERCREATE 90
fr. Function module
To Function module
Function group
‘You can ignore any pop-up informational messages
Repeat the same steps above to copy 2 more Function Modules remembering to replace 99 with your
group number
‘Copy From
ZCUSTOMERFINDBYNAME_XX
ZCUSTOMERGETRESERVATIONS_XX
Copy To
ZCUSTOMERFINDBYNAME_99
ZCUSTOMERGETRESERVATIONS_ 99
Select Local Objects from the dropdown box,
D (Class Library
> Cl Function Groups
‘© Expand the Funetion Groups and Function Modules to Display your copied objects
Local Onets a
Fen_00-2 iia)
[estore
"SNP REAP OGG
BC iass Library
> Di Function coups
= 700
© Gl Function Modules
‘ZCUSTOMERCREATE_99
-2CUSTOMERFINDBYNANE
‘ZCUSTOMERGETRESERVATIONS 29
‘ZCUSTOMERRESERVECAR_99
> Cincrutes
32 THE
Function Group for ABAP 00 Group 88
Create Cusiomer
Find Customer by Name
(Get Listof Customer Reservations
Reserve Carfor Customet
BEST-RUN BUSINESSES RUN SAP™ ew© Donble-click on ZCUSTOMERCREATE_XX (where XX is your group number) and then click
Activate|L,
SEIRSOIR HEINE ISS SISS Potent HERKEN eat
Siweesseceee
#150) (1a) assee@)
PEt
ogee cn eipaiB09 Sa
ete” Beaman
+ Using the Web Service Wizard, generate an Enterprise Service Definition for the function group ZFG_XX. (where XX
is your Group Number),
‘© Right mouse click on the function group, ZFG_XX, and choose Create->Other Objects->Enterprise
Service
returns + Cefn
atmos
Toners
33 THE BEST-RUN BUSINESSES RUN SAP’ ew* On the Provide Service Definition Details step. input the name of your service definition —
ZCustomerCarRental_XX(where XX is your Group Number). You can also enter a short description
(Kurzbeschreibung) and set the Endpoint Type to Function Group. Click Continue
aaa
© On the Choose Endpoint step, you have to specify the name of the fimetion group which will serve as
the implementation for this service definition. If you want to use Name Mapping (underscores are
removed and changed to camel case) you can check the Mapping of names option.
‘Eenseea S
34 THE BEST-RUN BUSINESSES RUN SAP’ ewOn the Choose Operations step, you can select which operations you wish to expose. Click Continue
: 2
+ On the Configure Service step, set the PRF_DT_IF_SEC_LOW profile in order to set the lowest
security level for this service definition. Be sure to check Deploy Service. If you forget to check this
box, you can complete this step later, manually from transaction code SOAMANAGER by creating
an Endpoint.
ToaPsepieston sessratre cesar
Poe
"Bear i st nt ase No TatesoT OTS
35 THE BEST-RUN BUSINESSES RUN SAP~ ew© On the Ener Package/Request step, please check Local Object to save the generated Service
Definition as local/private.
[Faeries 7
eo
—
. Qn the final step choose Complete, _ final step choose Complete.
HE BEST-RUN BUSINESSES RUN‘© Yon can optionally explore the Service Definition that was generated by the Wizard.
‘pay sera Deion ZCuremereaenta 0
‘eee
leo =)(s) /6r 6)
Rheims ins |
To start the SOA Manager, use the transaction code SCAMANAGER. (enter in SOAManager in the command field of
the system task bar). SOA Manager is used to complete the configuration of service providers and consumer proxies
a local ABAP system
Menu Edit Favorites Extras Help
SAP Easy Access - User menu
© The transaction SOAMANAGER should launch a Web Dynpro ABAP based application in your
Internet Browser. Choose the Service Administration tab and then click on Single Service
Administration.
‘© Inthe Web Service Administration screen that comes up, you can search for your Service Definition
(Hint use wildcard Z*XX where XX is your group number)
(Mir
ent ise =) senna 52 fre =)s sy OE] sect
GB zamnecoroes lrrowconssametomssesnarnene ye RUSIMTAMIEAL
37 THE BEST-RUN BUSINESSES RUN SAP™ ewSelect the row in the Search Results for your Service Definition and then click the Apply Selection
button. The bottom half of the screen will now show the details for the selected Service Definition,
| searen Recut
aera Nanespice
[+ @resonercerteris.se ep coredeouentereommhmetoneme tye
Gaza >
There are lots of changes that can be made to the Service Definition from this screen. You can see a
summary of all the settings from the Details tab. You can alter the published classification settings
from the Classification tab. From the Configurations tab. you see the Endpoints for this service. If you
had forgotten to Deploy Service during the wizard, you would now have to ereate this Endpoint
‘manually. The settings for the Endpoint were generated for us based upon the security profile we
choose during the wizard.
Go Back to Design Time Details
Web Service Configuration of Service Definition: ZCUSTOMERCARRENTAL
Back to Desion Tine Detats
Configuration of Web Service "ZCUSTOMERCARRENTAL": Endpoint ‘ZCustomerCarRenta”
* Click on the Overview tab
* Click on Open Web Service Navigator for the selected binding© A Separate Browser Window is started. If you are asked to login, enter the credentials Tester /
abed 1234
© The uil of wsdl is displayed. Click Next
Search Service Interfaces
Sowch Type: OWEEL OProvle Sytem OLogcalDestatn OSaics Rogicty
V9SOLURL: Ripon wa ep ar 10602
‘© If prompted for a login to download the wsdl ~ Please enter your userid and pwd for M30 and click OK
‘Select the ZCUSTOMERCREATE_XX operation (where XX is your group number) and Click Next
38 THE BEST-RUN BUSINESSES RUN SAP’ ewEnter your Group Number for the Customer Name and Click Next
‘© The system displays the input parameters and the result of the test.
© Click on the Operation link
40 THE BEST-RUN BSelect the ZCUSTOMERFINDBYNAME_XX operation (where XX is your group aumber) and Click
Next
* Enter your Group Number for the Customer Name Click Next,
© Important Please make note of your Customer ID (we will use this later).
4a THE BEST-RUN B© Click on the Operation link
ee
[it Previous |Next >|
“Service Information,
‘* Select the ZCUSTOMERRESERVECAR_ XX operation (where XX is your group number) and
Click Next
| Previous || Next i) [Invocation Parameters J invche ] | Aaut
Operations
© Enter a Category A and the CustomerID retuned from the ZCUSTOMERFINDBYNAME_XX
operation. Please be sure to enter the Start and End dates using the YYYY-MM-DD ISO date
format, Click Next
Parameters
— Gy Zeustomerreservecer’s: fy
0 ote * B18,
D aman» 2 17,
O cite * GET] 9,
2 sua « samo0 |g,
‘© The system displays the input parameters and the result of the test.
42 THE BEST-RUN BOptional — Set an External Breakpoint in Function Module: ZCUSTOMERRESERVECAR_XX (where XX is
{your group number) by right clicking inthe left margin and Set External Breakpoint afier which you can dots
from the WS Navigator into the ABAP system
Functenmotulo __2CSTORERRESEREECAR_99 ase
arenes |_ imo, Tattes | Exepéone
‘ple Bosksek “
wore | wer id ~ customer
ory akegery
exteption->get_text( }. ~
CATCH ey sot INTO Lo. exception.
return = 1o_exception->get_cext( )
exrr.
Lenstoner = ir seevies--get custoner by td| customer id |
#Youcan step dn ihe code using | #)4/64|("*)| Tye ABAP detmager has many powerful features
how to use it is essential for Java programmers accessing ABAP Business Logic.
4a THE BEST-RUN BUSINESSES RUN SA22000 by SAPAG
Alligus reseried. SAP, R°3, SAP Nenveaver, Duel, PannerEd9e, ByDeskgn, SAP Susiness ByOesign, ang.cier SAP products and services
iienkioned herein as wel as their respective logos are tindemarks or repistarad radamarks of SAP AG m Germany and other countries
Business Chjects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web inaligence, Xcelsius. and other
‘Business Objects products and services menoned Narain as wall a their respective loges ae Uademarks oF rapistered ademerks of Bsiness
Objects $ A inthe United States and nother countries. Buziness Cbjpets & an SAP company
Allother produc and wanvca rams menticnnd arp tho iradararks oftheir raspoct
Infomatonal purposes only. National product speciicsbons may wary
companies, Daa contained in this document areas
“These materals are subject to change without noice. These materials are provided by SAP AG end ts aftlleted companies SAP Group for
Infeertonsl purposes any, whoa reprosenistin ar waranty of sry ka, ard SAP Group shal nal be ibis for sors er ameene ve spot ts
tho malesinss The-onty werrarties for SAP Group products ary! sonvces fe those thal ro sot forth in the-expeess warranty statements
‘accompanying sun progucts and services, any. Neting herein sou Be construed as consttvtng an aodmonal waranty,
44 THE BEST-RUN BUSINESSES RUN SAP