Вы находитесь на странице: 1из 33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

SAP ABAP: Hands-On Test Projects with Business Scenarios

Recent

Topics
Tutorials

NEXT

PREV

Chapter 10: Interactive Lists

Highlights
Chapter 12: ABAP List Viewer
OutputsPart 1

CHAPTER11

Settings
Feedback

ABAPOOP

Sign Out

Introduction
Theincorporationofobjectorientationintotheformerlyprocedure
orientedABAPlanguageisanextensionoftheoriginal.WiththeOOP
extensioninanABAPprogram,youcanworkwithorwithoutthe
constructsofOOP.

Settings
10 days left in your trial. Subscribe.

Feedback

Thischapterproceedsonthepremisethatreadershaveanawarenessof
thefundamentalsofobjectorientedprogramming:classesand
interfacesinstancesorobjectsandthecomponentsofclassessuchas

Sign Out

attributes,methods,andevents.Readersknowaboutencapsulation,
inheritance,polymorphism,andvisibility.Andreadersunderstand
instanceattributes,instancemethods,andinstanceeventsclass
attributes,classmethods,andclasseventsandspecialmethods,event
handlermethods,etc.
IntheABAPenvironment,youcandefineandimplementclasseslocally
inanABAPprogram.Youcanusetheseclassesonlyintheprogram
whereyouhavelocatedthem,analogoustotheinternalsubroutines.You
candefineandimplementclassesgloballyintheclassbuilder
transactioncodeSE24.TheseclassescanbeusedinmultipleABAP
programs(reusable)analogoustothefunctionmodulelibrary.
Enjoy Safari? Subscribe Today

ThescopeofthischapterandofChapters12and13istoenableyoutouse
SAPsuppliedbuiltinclasses,especiallythebuiltinclassespertainingto
thegenerationofclassbasedlistsorreports(ALVreports.)Thesebuiltin
classeshaveeventsthatyouwilltrigger.Thetriggeringentailsexecution
ofmethodseventhandlermethodsinyourowndefinedclasses.Since
theseeventhandlermethodsarespecifictoascenarioorcontext(not
genericforthemostpart),itmakessensetolocatetheclassescontaining
theeventhandlermethodsintheABAPprogramitself(localclasses).You
canlocatetheseeventhandlermethods,ifyousodesire,inyourown
createdglobalclasses.Thischapterexposesyoutotheprocessofcreating
andmaintainingglobalclasses(i.e.,theclassbuilder)transactioncode
SE24.
Inthischapter,youwilllearntocreateandmaintainglobalclassbased
exceptionsanddeploytheseglobalclassbasedexceptionsforerror
conditionsinyourprograms,procedures,etc.Youwillalsolearnhowto
createanddeploycontextmenusthatinvolveusageofaclass.
TerminologyClarification:Thetermdataobjects,whichyouhave
beenusingsinceChapter2,willcontinuetocarrythesamemeaning.By
dataobjectswemean(a)WhateveryoudeclareinanABAPprogramwith
reservedwords:DATA,TABLES,CONSTANTS,alongwiththeliterals
theseconstitutetheinternaldataobjects.(b)TheDDICtables,views,and
structuresthefieldsofDDICtables,views,andstructuresthedata
elementstheDDICinternaltabledefinitions(tabletypes)these
constitutetheexternaldataobjects.(c)Thesystemfieldsconstitute
systemdataobjects.(d)ThePARAMETERSvariablesandtheSELECT
OPTIONSvariablestheseconstitutethespecialdataobjects.
YourefertothecomponentsofDDICsuchastabledefinitions,data
elements,anddomains,etc.,asDDICobjects.Thewordobjectisused
herenotinthecontextofOOP.
LocalClassSyntaxes:Definition,Implementation,Declaration

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

1/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

ofMethods,CallingMethods
First,therewillbecoverageoflocalclassesandtheconnectedsyntaxes.
Theessentialsofsyntaxesaredescribed.Fordetailedsyntaxes,youcan
refertotheonlinedocumentation.
ClassDefinition:
Thesyntaxofalocalclassdefinition:

CLASS<classname>DEFINITION.
PUBLICSECTION.
TYPEPOOLS:....
TYPES:.....
COMSTANTS:.....
DATA:....
CLASSDATA:.....
METHODS:<method1>...
CLASSMETHODS<classmethod1>...
EVENTS:...
CLASSEVENTS.....
INTERFACES..
PROTECTEDSECTION.
........
.....
PRIVATESECTION.
......
.......
ENDCLASS.

Anexplanationofthedifferenttermsofthesyntaxfollows.
VisibilityofComponents
PUBLICSECTION:Thecomponentsdeclaredinthissectionare
accessibletoalltheusersoftheclasstoothermethodsoftheclassand
inheritedclasses,ifany.
PROTECTEDSECTION:Thecomponentsdeclaredinthissectionare
accessibletomethodsoftheclassandinheritedclasses,ifany.
PRIVATESECTION:Thecomponentsdeclaredinthissectionare
accessibleonlyinmethodsoftheclass.
Theprefix'CLASS'isusedtodeclarestaticcomponents.
Syntactically,alloftheaboveareoptional.Practically,aclasscould
containattributes(DATAand/or
CLASSDATA),methods(METHODS
and/orCLASSMETHODS),andevents(EVENTSand/orCLASS
EVENTS)inoneormoreofthethreesections:PUBLIC,PROTECTED,
andPRIVATE.Theclasscouldcontainotherstatements:TYPES,
CONSTANTS,etc.,asmentionedinthesyntaxabove.
DeclarationofMethods
Intheclassorinterfacedefinition,methodsaredeclaredusingthe
followingsyntax:

METHODS<methodname>
[IMPORTING<ip1>TYPE<type>[OPTIONAL|DEFAULT<defaultvalue>].....]
[EXPORTING<ep1>TYPE<type>[OPTIONAL|DEFAULT<defaultvalue>].....]
[CHANGING<cp1>TYPE<type>[OPTIONAL|DEFAULT<defaultvalue>].....]
[RETURNING<rp>TYPE<type>[OPTIONAL|DEFAULT<defaultvalue>]]
[{RAISING|EXCEPTIONS}exc1exc2...].

Parameters:
ThesoleRETURNINGparameterisforthefunctionalmethods.The
functionalmethodcanhaveanynumberofIMPORTINGparametersand
oneRETURNINGparameter.Afunctionalmethodwillnothaveany
EXPORTINGandCHANGINGparameters.
AneventhandlermethodwillhaveonlyIMPORTINGparameter.A
CONSTRUCTORmethodwillhaveonlyIMPORTINGparameter.For
therestofmethods,therecanbeanynumberofIMPORTING,
EXPORTING,CHANGINGparameters.Theparameterscanbepassed
bythefollowing:
Reference:REFERENCE(<ip1>)or<ip1>
Value:VALUE(<ip1>)
IfEXPORTING,CHANGING,orRETURNINGparametersarespecified
suchasVALUE(<ep1>),VALUE(<cp1>),andVALUE(<rp>),the
parametersarepassedbyvalueandresult.
ParameterTYPES:
AlltheparametershavetobeassignedTYPES.TheTYPESassignedwill
bematchedwiththerespectiveTYPESofactualparameters,anda

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

2/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

mismatchwillresultinanerror.TheTYPESthatcanbeassigned:
GenericABAPTypesRefertothetableintheonline
documentationwiththefollowingpath:
ABAPByTheme

BuiltInTypes,DataObjectsandFunctions

Locallydeclared,DDICTYPESincludingdataelements,DDIC
dataobjects,andsystemfields.
TheOPTIONALclauseistoindicatethattheparameterisoptional,not
mandatory.TheDEFAULTclauseistoindicateadefaultvalue.Eitherof
theOPTIONALorDEFAULTclausescanbespecified.IftheDEFAULT
clauseisgiven,theparameterisoptional.
Exceptions:
ThekeywordRAISINGistobeusedforclassbasedexceptionsandthe
keywordEXCEPTIONSusedfortheerrorconditionswiththeMESSAGE
statement(nonclassbased).Theparametersalongwiththeexceptions
arecalledthesignaturesofthemethods.
Havingcoveredclassdefinitionsyntax,weproceedtothesyntaxofclass
implementation.
ClassImplementation
Thesyntaxofalocalclassimplementation:

CLASS<classname>IMPLEMENTATION.
METHOD<method1>.
.....
.....
ENDMETHOD.
METHOD:<method2>.
.....
.....
ENDMETHOD.
......
.....
ENDCLASS.

CallingMethods,ReferringtoAttributes
Touseaclassasanobjecttocreateaninstanceofaclassyouhaveto
firstdeclareareferencevariablewiththeDATAstatementreferringto
theclass:
DATA:CREFTYPEREFTO<classname>.

Youcreateaninstanceofaclasswiththecreatestatement(executesthe
CONSTRUCTORmethod):
CREATEOBJECTCREF[IMPORTING<importingparameters>].

Withthisstatement,thereferencevariableCREFcontainsareferenceto
aninstanceoftheclass.
Thesyntaxforcallinganinstancemethod(similartocallingafunction
module):

CALLMETHODCREF><methodname>
[IMPORTING<ifp1>=<iap1>...]
[EXPORTING<efp1>=<eap1>...]
[CHANGING<cfp1>=<cap1>...]
[EXCEPTIONS
<exception1>=1
....]
.
where
<.fp.>formalparameters
<.ap.>actualparameters

Torefertoanattributeofaninstanceofaclass:
CREF><attributename>

Astaticmethodwillbecalledwiththefollowingsyntax:

CALLMETHOD<classname>=><methodname>
[IMPORTING<ifp1>=<iap1>...]
[EXPORTING<efp1>=<eap1>...]
[CHANGING<cfp1>=<cap1>...]
[EXCEPTIONS
<exception1>=1
....]
.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

3/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

Torefertoastaticattributeofaclass:

<classname>=><staticattributename>

>Forreferringtoaninstanceattribute,instancemethod,etc.
=>Forreferringtoastaticattribute,staticmethod,etc.
InterfaceDeclaration
Thefeaturesofinterfaceandinheritanceareusedtoimplement
polymorphism.Thesyntaxofaninterfacedeclarationisasfollows:
INTERFACE<interfacename>.
......
ENDINTERFACE.

Youcandefinethesamecomponentsinaninterfaceasinaclass(i.e.,
attributes,methods,events,etc.).Thereisnoconceptofvisibilityinthe
interface.Thecomponentsofaninterfacebelongtothepublicsectionof
theclasseswheretheinterfaceisimplemented.Toimplementan
interfaceinaclass,youhavetoincludetheinterface:

CLASS<classname>DEFINITION.
PUBLICSECTION.
.....
INTERFACES:<interfacename>..
.....

Inaclasswithanincludedinterface,theinterfacecomponentscanbe
referredtoas<interfacename>~<componentname>.
Interfacemethodswillbeimplementedbymorethanoneclass,andthey
willbeimplementeddifferentlyindifferentclasses.
Youcandeclarereferencevariableswithreferencestointerfaces:
DATA:IF_REFTYPEREFTO<interfacename>.

Havingbeenintroducedtotheessentialsoftheclasssyntax,youwill
nowperformhandsonexercises.
HandsonExercise:DefineandImplementaSimpleLocalClass
(MethodtoConcatenateaTextArrayintoaString)
Thishandsonexerciseistoexposeyoutobasicsyntaxesratherthan
implementintricatefunctionalities.The
handsonexerciseclasshasa
singlemethod.Thismethodtakesanimportparameter,aninternaltable
(elementarytextarray),andconcatenatestheindividualrowsintoone
string,whichisareturningparameter.
Theexercisemightseemabittrivial,buttheobjectiveistogetthehang
ofthesyntax.
Youloadthetextarrayintheprogramwiththenameofthemonthsfrom
thedatabasetexttableT247.Youcouldhaveloadedanytextintothetext
array.
Theprogramcode:

REPORTYCL_CH11_01_BEAD_STRINGS_LCLAS.
**************************************
*LocalClassWithOneMethod:**
*ConcatenaterowsOfAnArray**
**************************************
CLASSOWN_LOCAL_CLASSDEFINITIONDEFERRED.
"classnotdefinedyet
DATA:CL_REFTYPEREFTOOWN_LOCAL_CLASS,
RESULTTYPESTRING,
STRING_TABLTYPESTRING_TABLEWITHHEADERLINE.
"DDICTABLETYPE(arrayofTYPESTRING)
****************classdefinition*************************
CLASSOWN_LOCAL_CLASSDEFINITION.
**************************************************
*classcontainsonemethod:BEAD_STRINGS**
***
*themethodtakestwoimportparameters:**
*(1)anarrayofDDICTYPESTRING_TABLEwhose**
*lineisTYPESTRING**
*(2)separatorcharacterbetweenthewordsof**
*concatenatedstring.DEFAULTis''**
***
*concatenatesalltherowsofthearray&**
*returnsasinglestringofTYPESTRING**
***
*themethodhasoneexception.checksforno**
*datainthearraySTR_TABNO_DATA**
***
*thisisafunctionalmethod.canbeusedin**

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

4/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

*expressionsthoughnotinWRITEstatement.**
*theWRITEstatementdoesnotsupportfunctions**
*initsusage**
**************************************************
PUBLICSECTION.
METHODSBEAD_STRINGSIMPORTING
VALUE(STR_TAB)TYPESTRING_TABLE
VALUE(SEPARATOR)TYPECDEFAULT''
RETURNING
VALUE(STRNG)TYPESTRING
EXCEPTIONSNO_DATA.
PRIVATESECTION.
DATA:STRTYPESTRING.
ENDCLASS.
****************classimplementation*********************
CLASSOWN_LOCAL_CLASSIMPLEMENTATION.
METHODBEAD_STRINGS.
DESCRIBETABLESTR_TAB..
IFSYTFILL=0.
MESSAGES035(YCL_CH07_MCLASS01)RAISING
NO_DATA.
ENDIF.
LOOPATSTR_TABINTOSTR.
IFSYTABIX>1.
CONCATENATESTRNGSTRINTOSTRNGSEPARATED
BYSEPARATOR.
ELSE.
STRNG=STR.
ENDIF.
ENDLOOP.
ENDMETHOD.
ENDCLASS.
*****************************************************
STARTOFSELECTION.
SELECTLTXFROMT247INTOSTRING_TABL
WHERESPRAS=SYLANGU.
APPENDSTRING_TABL.
ENDSELECT.
CREATEOBJECTCL_REF.
**CALLMETHODCL_REF>BEAD_STRINGS
**EXPORTING
**STR_TAB=STRING_TABL[]
**SEPARATOR=''
**RECEIVING
**STRNG=RESULT.
**
RESULT=CL_REF>BEAD_STRINGS(STR_TAB=STRING_TABL[]
SEPARATOR='').
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4
DISPLAYLIKE'E'.
ELSE.
WRITE:/5RESULT.
ENDIF.

Afunctionmethodcanbeusedinanexpression(likeyouaredoinginthe
program)orcanbeinvokedwiththeCALLMETHOD...statement.You
cancommenttheexpressionanddecommenttheCALLMETHOD...
statementintheprogramandseetheresults.
TheprogramoutputwilllooklikeFigure111.

Figure111.Program:YCL_CH11_01_BEAD_STRINGS_LCLAS
Output

Thiswasanexampleofasimplemethodinalocallydefinedand
implementedclass.
HandsonExercise:DefineandImplementaSimpleGlobalClass
(MethodtoConcatenateaTextArrayintoaString)
Youwillimplementamethodofconcatenatingrowsofatextarrayina
globalclasssothatyouareexposedtotheprocessofcreating(i.e.,
definingandimplementingaglobalclass).
Tomaintainglobalclasses,executethetransactioncodeSE24to

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

5/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

navigatetotheclassbuilder.Enterthenameoftheclassas
YCL_CH11_CL_STRING_OPERATIONS.(Theclassnamemuststart
withY/Zandhaveamaximumnamespaceofthirtycharacters.)Press
thecreatebuttonorthefunctionkeyF5.Figure112willappear.

Figure112.GlobalClass:
YCL_CH11_CL_STRING_OPERATIONSInitialScreen

Enterthedescription.Acceptthedefaultsforotherfields.ClicktheSave
button.Thesystemwillpromptforapackage($TMP).Afterthepackage
isassigned,Figure113willappear.

Figure113.GlobalClass:YCL_ch11_CL_STRING_OPERATIONS
MethodsTab

ThereareeighttabsthesystembydefaulttakesyoutotheMethodstab.
TheinformationinthePropertiestab,likeinanyotherABAPworkbench
object,ismaintainedbythesystem(user,datecreated,package,etc.).
Correspondingtothedataobjectyoudeclaredintheprivatesectionofthe
localclass,youneedtocreateanattributeintheprivatesectioninthe
globalclass.So,clickontheAttributestab.Enterthenameoftheattribute
asSTR,thelevelasInstanceAttribute(otheroptionsareStaticAttribute
andConstant)visibilityasPrivate,andtheassociatedtypeasSTRING.
ThescreenwiththeenteredvalueswilllooklikeFigure114.

Figure114.GlobalClass:
YCL_CH11_CL_STRING_OPERATIONSAttributesTab

ThiswasequivalenttodeclaringthedataobjectSTRintheprivate
sectionofthelocalclass.
NowclickontheMethodstab.Enterthenameofthemethodas
BEAD_STRINGS,levelasInstanceMethod,andvisibilityasPublic.The
screenwithenteredvalueswilllooklikeFigure115.

Figure115.GlobalClass:
YCL_CH11_CL_STRING_OPERATIONSMethodsTab

Next,youneedtoenterthemethodparameters.Soclickonthe
parametersbutton.ThemethodBEAD_STRINGShastwoimporting
parametersandonereturningparameter.
SoenterthenameofthefirstimportingparameterasSTR_TAB,typeas
Importing,andenablethePassValuecheckboxfortheparametertobe
passedbyvalueentertheassociatedtypeasSTRING_TABLE.
EnterthenameofthesecondimportingparameterasSEPARATOR,
typeasImportingenablethePassValuecheckboxfortheparameterto
bepassedbyvalueentertheassociatedtypeasCenterthedefault
valueas.Thesystemautomaticallyenablestheparameteroptional
checkbox.
EnterthereturningparameterasSTRNG,typeasReturning,and
enablethePassValuecheckboxfortheparametertobepassedbyvalue

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

6/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

andresultandtheassociatedtypeasSTRING.
ThemethodparametersscreenwiththeenteredvalueslookslikeFigure
116.

Figure116.Method:BEAD_STRINGSMethodParameters

Youneedtoentertheexceptions.ClicktheExceptionstab.Thescreen
withtheexceptionNO_DATAenteredwilllooklikeFigure117.

Figure117.Method:BEAD_STRINGSMethodExceptions

ClickontheMethodsbuttontoreturntothemethodsscreen.Youhaveto
entertheprogramcodeforthemethod.Sodoubleclickonthemethod
name.Thescreenwillpromptforsaving.ClicktheSavebutton.The
screenthenwillpresentthetemplateforthemethod:

methodBEAD_STRINGS.
endmethod.

Copythelinesfromthelocalclassmethodbetweenthelinesmethod...
andendmethod.
methodBEAD_STRINGS.
DESCRIBETABLESTR_TAB..
IFSYTFILL=0.
MESSAGES035(YCL_CH07_MCLASS01)RAISING
NO_DATA.
ENDIF.
LOOPATSTR_TABINTOSTR.
IFSYTABIX>1.
CONCATENATESTRNGSTRINTOSTRNGSEPARATED
BYSEPARATOR.
ELSE.
STRNG=STR.
ENDIF.
ENDLOOP.
endmethod.

Performasyntaxcheckoftheprogramcode.Gobacktothemethod
screen.Checkforconsistency.Activatetheclass.Theclassactivation
involvesmultiplecomponents,andthescreenwilllooklikeFigure118.

Figure118.GlobalClass:
YCL_CH11_CL_STRING_OPERATIONSActivation

Theclassisreadyforuse.TheABAPprogramcodewherethemethod
BEAD_STRINGSofthisclassisbeingused:

REPORTYCL_CH11_02_BEAD_STRINGS_GCLAS.
*********************************************
*UseMethodBEAD_STRINGSinGlobalClass:**
*YCL_CH10_CL_STRING_OPERATIONS**
*********************************************
DATA:CL_REFTYPEREFTOYCL_CH11_CL_STRING_OPERATIONS,
RESULTTYPESTRING,
STRING_TABLTYPESTRING_TABLE.
STARTOFSELECTION.
SELECTLTXFROMT247INTOTABLESTRING_TABL
WHERESPRAS=SYLANGU.
CREATEOBJECTCL_REF.
*CALLMETHODCL_REF>BEAD_STRINGS
*EXPORTING
*STR_TAB=STRING_TAB
*SEPARATOR=''
*RECEIVING

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

7/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

*STRNG=RESULT
*EXCEPTIONS
*NO_DATA=1
*others=2
*.
*IFSYSUBRC<>0.
*MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
*WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4.
*ENDIF.
RESULT=CL_REF>BEAD_STRINGS(STR_TAB=STRING_TABL[]
SEPARATOR='').
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4
DISPLAYLIKE'E'.
ELSE.
WRITE:/5RESULT.
ENDIF.

Theoutputisthesameasthatobtainedwiththelocalclass(Figure119).

Figure119.Program:YCL_CH11_02_BEAD_STRINGS_GCLAS
Output

Youweregeneratingtheprogramcodeforcallingafunctionmodulein
Chapter7entitledModularization(insidetheABAPeditor,themenu
option:Edit

Patternetc.).Thesamefacilitycanbeavailedto

generateprogramcodeforcallingamethod.Thescreenwhenyou
choose,insidetheABAPeditor,themenuoptionEdit

Patternis

showninFigure1110.

Figure1110.GenerateCodeABAPEditorOption:Edit
Pattern

ClickonthesecondradiobuttonABAPObjectsPatterns.Pressthe
continuebutton/<enterkey>.Thescreenwiththeenteredvalueswill
appearlikeFigure1111.

Figure1111.GenerateCodeForCallingaMethod

Youenteredthenameofthereferencevariable(instanceorobject),the
globalclassname,andselectedthemethodoftheclassfromtheselection
list.
Inthisdialoguebox,youcangenerateprogramcodeforCREARE
OBJECT...,RAISEEVENT...,andRAISEEXCEPTIONstatementsby
selectionofrespectiveradiobuttons.
Youcreatedaglobalclassintheclassbuilderanddeclaredand
implementedamethodinthisglobalclass.Thenyouinvokedthemethod
fromanexecutableABAPprogram.
HandsonExercise:GlobalClass(MethodtoSplitaString
withoutBreakingaWord)
InChapter7,entitledModularization,youcreatedafunctionmodule

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

8/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

thatsplitastringintomultiplestringsofspecifiedlengthincharacters
withoutbreakingaword.Thenameofthisfunctionmodulewas
YCL_CH07_SPLIT_STRING.Youwillnowimplementthesame
functionalityinamethodusingtheglobalclassyoucreatedinthe
previousexercise.
ThefunctionmodulesacceptthetypeTABLESparameter.Thistypeof
parameterisnotavailableformethodsofaclass(onlyIMPORTING,
EXPORTING,CHANGING,andRETURNING).WithaTABLES
parameterinafunctionmodule,youwereimplicitlygettingaworkarea
ofthesamename(HEADERLINE)astheformalTABLESparameter
name.Inthepresentcontext,theworkareaisexpectedtobean
elementaryTYPECdataobject.Youneedtheworkareatodetermine
thelengthincharactersoftheoutputstringaswellneedingitinthe
APPENDstatement.
Withintheglobalclass,inthemethodtosplitastring,youarecreating
theworkareaatruntimeusingtheCREATEDATA...statement
introducedinChapter8entitledOpenSQLDataRetrieval.The
statement:

CREATEDATASREFLIKELINEOFSTABLE.

YouarethendereferencingthereferencevariableSREFandassigning
ittoafieldsymboltobeabletoaddresstheruntimecreateddataobject:

ASSIGNSREF>*TO<WA>.

Inthefunctionmodule,youwerecheckingthetypeofinputparameter
andraisinganexceptioniftheinputtypeisnotCorSTRING.Inthe
class,thisistakenofcarebythesystem.Sinceparametershavetobea
compulsorilyassignedtype,youhaveassignedtheABAPgenerictype
CSEQUENCE(CorSTRING).Thesystematruntimewillcheckthe
typeoftheactualparameter,andamismatchwillresultinanerror
condition.Soyouaresavedtheeffortofcheckingthetypeofinput
parameter.
Youhaveaddedanadditionalexceptioncheckingfornoinputdata.
Therestofthemethodprogramcodeisthesameastheprogramcodeof
thefunctionmoduleYCL_CH07_SPLIT_STRING.
Youcannavigatetotheclassbuilder(transactioncodeSE24)enterthe
classnameasYCL_CH11_CL_STRING_OPERATIONSandclickonthe
changebutton.
EnterthemethodnameSPLIT_STRINGunderthefirstmethodyou
createdintheprevioushandsonexercise.Thescreenwilllooklike
Figure1112

Figure1112.Class:YCL_CH11_CL_STRING_OPERATIONS
MethodSPLIT_STRING

.
Positionthecursoronthesecondrow(i.e.,methodSPLIT_STRING).
ClickontheParametersbutton.Thescreenafterentryoftheparameters
willlooklikeFigure1113.

Figure1113.MethodSPLIT_STRING:Parameters

ClickontheExceptionsbutton.ThescreenafterentryofExceptionswill
looklikeFigure1114.

Figure1114.MethodSPLIT_STRING:Exceptions

ClickontheMethodbutton.Thendoubleclickonthemethod
SPLIT_STRING.ThescreenwillpresentthemethodtemplateinFigure

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

9/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

1115.

Figure1115.MethodSPLIT_STRING:MethodTemplate

Theprogramcodeofthemethod:
methodSPLIT_STRING.
DATA:WORDTYPESTRING,"storeextractedword
TYP(1)TYPEC,"storevariableTYPE
LENTYPEI,"storelengthofstring
CLENTYPEI,"storeavailablecharacters/columns
WLENTYPEI,"storeextractedwordlength
SREFTYPEREFTODATA."refvariableforlineofSTABLE
FIELDSYMBOLS:<WA>TYPEANY."fieldsymboltoaddresslineofSTABLE
************************************
CREATEDATASREFLIKELINEOFSTABLE.
ASSIGNSREF>*TO<WA>.
DESCRIBEFIELD<WA>TYPETYP."<WA>referencetotheelementary
"dataitemi.e.lineofSTABLE
IFTYP<>'C'.
MESSAGES007(YCL_CH07_MCLASS01)RAISING
RETURN_TABLE_ELEMENT_NOT_TYPEC.
ENDIF.
IFSTRING_TO_SPLITISINITIAL.
MESSAGES035(YCL_CH07_MCLASS01)RAISING
EMPTY_STRING.
ENDIF.
REFRESHSTABLE[]."clearinternaltableofexistingrows
DESCRIBEFIELD<WA>LENGTHLENINCHARACTERMODE.
"getlengthofelement
CLEN=LEN.
DO.
IFSTRING_TO_SPLITISINITIAL.
EXIT.
ENDIF.
SEARCHSTRING_TO_SPLITFOR'..'."SEARCHforembeddedblank
IFSYSUBRC<>0."lastwordinthetext
WORD=STRING_TO_SPLIT.
STRING_TO_SPLIT=''.
ELSE.
SPLITSTRING_TO_SPLITAT''INTOWORDSTRING_TO_SPLIT.
ENDIF.
WLEN=STRLEN(WORD).
IFSYINDEX=1.
<WA>=WORD.
ELSEIFWLEN<=CLEN.
CONCATENATE<WA>WORDINTO<WA>SEPARATEDBY''.
ELSE.
APPEND<WA>TOSTABLE[].
<WA>=WORD.
CLEN=LEN.
ENDIF.
CLEN=CLENWLEN1.
ENDDO.
IF<WA><>''.
APPEND<WA>TOSTABLE[].
ENDIF.
endmethod.

Youhavedeclareddatainsidethemethod.Thisislocaltothemethod.In
thepreviousmethodBEAD_STRINGS,youwereusinganattributeSTR
declaredinthePRIVATEsectionoftheclass.Youcouldhaveaswell
declaredthisinsidetheclass.Theideawastocreateanattribute.An
attributeinthePRIVATEsectionofaclasscanbeaccessedbytheentire
class,anddatadeclaredwithinamethodcanbeaccessedonlywithinthat
method.
Save,performaconsistencycheck,andreactivatetheclass
YCL_CH11_STRING_OPERATIONSagain.Theactivatingscreenis
showninFigure1116.

Figure1116.Class:YCL_CH11_CL_STRING_OPERATIONS
Reactivation

Thesourceprogramusingthismethodis,first,callingthefunction
moduleSPELL_AMOUNT,whichisconvertingtheinputfigureor

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

10/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

amountintoonelineoftext.Next,youarecallingthemethod
SPLIT_STRINGtosplittheonelineoftextintomultiplelines.
Thesource:
REPORTYCL_CH11_03_SPLIT_STRING_GCLAS.
****************************************
*CallMethodSPLIT_STRINGInClass:**
*YCL_CH11_CL_STRING_OPERATIONS**
****************************************
DATA:STRG(30)TYPEC,
STRGALIKESTANDARDTABLEOFSTRG,
ISTRTYPESTRING,
SPELLTYPESPELL,
SPLIT_REFTYPEREFTOYCL_CH11_CL_STRING_OPERATIONS.
*****************************************************
PARAMETERS:AMT(7)TYPEPDECIMALS2DEFAULT
'987654321.50'.
STARTOFSELECTION.
CALLFUNCTION'SPELL_AMOUNT'
EXPORTING
AMOUNT=AMT
CURRENCY='INR'
FILLER=''
LANGUAGE=SYLANGU
IMPORTING
IN_WORDS=SPELL
EXCEPTIONS
NOT_FOUND=1
TOO_LARGE=2
OTHERS=3
.
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4.
ENDIF.
CONCATENATESPELLWORDSPELLDECWORDINTOISTR
SEPARATEDBY''.
CREATEOBJECTSPLIT_REF.
CALLMETHODSPLIT_REF>SPLIT_STRING
EXPORTING
STRING_TO_SPLIT=ISTR
IMPORTING
STABLE=STRGA
EXCEPTIONS
RETURN_TABLE_ELEMENT_NOT_TYPEC=1
EMPTY_STRING=2
others=3
.
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4
DISPLAYLIKE'E'.
ELSE.
LOOPATSTRGAINTOSTRG.
WRITE:/5STRG.
ENDLOOP.
ENDIF.

TheinputandoutputscreenswillbelikethoseinFigures1117and1118.

Figure1117.Program:YCL_CH11_03_SPLIT_STRING_GCLAS
Input

Figure1118.Program:YCL_CH11_03_SPLIT_STRING_GCLAS
Output

Youlocatedanothermethodinanexistingglobalclasscreatedinthe
precedinghandsonexercise.Themethodsplitsalineofstringinto
multiplelineswithoutbreakingaword.Themethodimplements
functionalityimplementedearlierwithafunctionmoduleinChapter7.
HandsonExercise:DefineLocalInterface,ImplementInterface
MethodinLocalClasses(MethodtoFetchBusinessPartner
Name&Address)
Scenario
Customersandvendors/suppliersarebusinesspartners.Giventhecode
ofthebusinesspartner,fetchingthenameandaddressofcustomers

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

11/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

involvesretrievingdatafromthedatabasetableKNA1,andfetchingthis
sameinformationofvendorsinvolvesretrievingdatafromthedatabase
tableLFA1.
Alocalinterfacehasbeendefinedinwhichamethodisdeclared.This
methodhasanimportingparameterasthebusinesspartnercodeand
exportingparametersasthenameandaddressofthebusinesspartner.
Twodifferentlocalclassesimplementthismethod.Oneclassretrieves
nameandaddressdatafromthedatabasetableKNA1,andtheotherclass
retrievesnameandaddressdatafromthedatabasetableLFA1.
Thiscouldhavebeenachievedwithsimpleconditionalstatements
withoutaninterfaceandclasses.Theideaistoillustratetheusageof
interfaceanditsbasicsyntaxesastheyexistinABAP.
Thesourcecode:
REPORTYCL_CH10_04_LOCAL_IF_CLASS.
*****************************************************
*DemolocalINTERFACE(polymorphism)andsyntaxes**
*****************************************************
***********************************************************
*ontheSELECTIONSCREENinput:**
*(1)businesspartner/partnertype:customerorvendor**
*(2)customer/vendorcode**
***
*usingthefeatureofINTERFACEdeclaredmethodandthis**
*methodimplementedintwodifferentclasses,the**
*addressofcustomer/vendorisretrievedandoutput**
***
*samemethodindifferentclassesgetsdifferentinfo**
***
*themethodGET_ADDRESSinclassGET_CUST_ADDRretrieves**
*thecustomeraddressfromdatabasetableKNA1**
***
*themethodGET_ADDRESSinclassGET_VEND_ADDRretrieves**
*thevendoraddressfromdatabasetableLFA1**
***
*thename,addressfields:NAME1STRASORT01PSTLZare**
*common/sameindatabasetablesKNA1&LFA1**
***
*exceptionraisedusingMESSAGEstatement.subsequently**
*classbasedexceptioniscovered**
***********************************************************
TYPES:TYP_BPCODE(10)TYPEC."businesspartnercodeTYPE
CLASS:GET_CUST_ADDRDEFINITIONDEFERRED,"CLASSyettobedefined
GET_VEND_ADDRDEFINITIONDEFERRED."ditto
INTERFACE:IF_GET_PARTNER_ADDRDEFERRED.
"INTERFACEyettobedeclared
DATA:CUST_ADDRTYPEREFTOGET_CUST_ADDR,
"customeraddress
VEND_ADDRTYPEREFTOGET_VEND_ADDR,
"vendoraddress
IF_PARTNER_ADDRTYPEREFTOIF_GET_PARTNER_ADDR,
PARTNER_TP(1)TYPECVALUE'C',
BPCODETYPETYP_BPCODE,
NAME1TYPENAME1_GP,
STRASTYPESTRAS_GP,
ORT01TYPEORT01_GP,
PSTLZTYPEPSTLZ.
*********************INTERFACE*************************
INTERFACEIF_GET_PARTNER_ADDR.
"convention:startinterfacenameswithIF_
METHODS:GET_ADDRESSIMPORTINGVALUE(BPCODE)TYPETYP_BPCODE
EXPORTINGPNAMETYPENAME1_GP
PSTREETTYPESTRAS_GP
PCITYTYPEORT01_GP
PPINTYPEPSTLZ
EXCEPTIONSINVALID_CODE.
ENDINTERFACE.
******classdefinition,implementationforcustomerinfo******
CLASSGET_CUST_ADDRDEFINITION."custmeraddress
PUBLICSECTION.
INTERFACESIF_GET_PARTNER_ADDR.
"interfacesusedbyclassspecified
PRIVATESECTION.
DATA:KNA1TYPEKNA1.
ENDCLASS.
CLASSGET_CUST_ADDRIMPLEMENTATION.
METHODIF_GET_PARTNER_ADDR~GET_ADDRESS.
"qualifyinginterfacemethodinthiswaywith~(tilde)
SELECTSINGLE*FROMKNA1INTOKNA1WHEREKUNNR=BPCODE.
IFSYSUBRC<>0.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

12/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

MESSAGES036(YCL_CH07_MCLASS01)RAISING
INVALID_CODEWITHBPCODE.
ENDIF.
PNAME=KNA1NAME1.
PSTREET=KNA1STRAS.
PCITY=KNA1ORT01.
PPIN=KNA1PSTLZ.
ENDMETHOD.
ENDCLASS.
******classdefinition,implementationforvendorinfo******
CLASSGET_VEND_ADDRDEFINITION.
PUBLICSECTION.
INTERFACESIF_GET_PARTNER_ADDR.
"interfacesusedbyclassspecifiedlikethis
PRIVATESECTION.
DATA:LFA1TYPELFA1.
ENDCLASS.
CLASSGET_VEND_ADDRIMPLEMENTATION.
METHODIF_GET_PARTNER_ADDR~GET_ADDRESS.
"qualifyinginterfacemethodinthiswaywith~(tilde)
SELECTSINGLE*FROMLFA1INTOLFA1WHERELIFNR=BPCODE.
IFSYSUBRC<>0.
MESSAGES037(YCL_CH07_MCLASS01)RAISING
INVALID_CODEWITHBPCODE.
ENDIF.
PNAME=LFA1NAME1.
PSTREET=LFA1STRAS.
PCITY=LFA1ORT01.
PPIN=LFA1PSTLZ.
ENDMETHOD.
ENDCLASS.
*********************
*SELECTIONSCREEN**
*********************
SELECTIONSCREENSKIP1.
SELECTIONSCREENBEGINOFBLOCKBL1WITHFRAMETITLE
COM1NOINTERVALS.
SELECTIONSCREENSKIP1.
SELECTIONSCREENBEGINOFLINE.
PARAMETERS:CUSTRADIOBUTTONGROUPGR1USERCOMMAND
PART_TYPEDEFAULT'X'.
SELECTIONSCREENCOMMENT3(15)COM2.
PARAMETERS:VENDRADIOBUTTONGROUPGR1.
SELECTIONSCREENCOMMENT21(15)COM3.
SELECTIONSCREENENDOFLINE.
SELECTIONSCREENSKIP1.
SELECTIONSCREENBEGINOFLINE.
SELECTIONSCREENCOMMENT1(14)COM4FORFIELDCUST_CD
MODIFIDCG1.
PARAMETERS:CUST_CDLIKEKNA1KUNNRMODIFIDCG1.
SELECTIONSCREENENDOFLINE.
SELECTIONSCREENBEGINOFLINE.
SELECTIONSCREENCOMMENT1(14)COM5MODIFIDCG2
FORFIELDVEND_CD.
PARAMETERS:VEND_CDLIKELFA1LIFNRVALUECHECK
MODIFIDCG2.
SELECTIONSCREENENDOFLINE.
SELECTIONSCREENSKIP1.
SELECTIONSCREENENDOFBLOCKBL1.
***********************************
INITIALIZATION.
COM1='SelectBusinessPartnerType'(001).
COM4='CustomerCode:'(004).
COM5='VendorCode:'(005).
COM2='Customer'(002).
COM3='Vendor'(003).
***********************************************
***********************************************
ATSELECTIONSCREENOUTPUT.
IFCUST='X'.
PARTNER_TP='C'.
ELSE.
PARTNER_TP='V'.
ENDIF.
LOOPATSCREEN.
IFSCREENGROUP1<>'CG1'ANDSCREENGROUP1<>'CG2'.
CONTINUE.
ENDIF.
IF(SCREENGROUP1='CG1'ANDPARTNER_TP='C')OR
(SCREENGROUP1='CG2'ANDPARTNER_TP='V').
SCREENINPUT=1.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

13/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

SCREENACTIVE=1.
SCREENINVISIBLE=0.
ELSEIF(SCREENGROUP1='CG1'ANDPARTNER_TP<>'C')OR
(SCREENGROUP1='CG2'ANDPARTNER_TP<>'V').
SCREENINPUT=0.
SCREENACTIVE=0.
SCREENINVISIBLE=1.
ENDIF.
MODIFYSCREEN.
ENDLOOP.
****************mainprocessing**************
STARTOFSELECTION.
CREATEOBJECTCUST_ADDR.
CREATEOBJECTVEND_ADDR.
IFCUST='X'.
BPCODE=CUST_CD.
IF_PARTNER_ADDR=CUST_ADDR."UP/WIDECASTING
ELSE.
BPCODE=VEND_CD.
IF_PARTNER_ADDR=VEND_ADDR."UP/WIDECASTING
ENDIF.
********************
CALLMETHODIF_PARTNER_ADDR>GET_ADDRESS
EXPORTING
BPCODE=BPCODE
IMPORTING
PNAME=NAME1
PSTREET=STRAS
PCITY=ORT01
PPIN=PSTLZ
EXCEPTIONSINVALID_CODE=4.
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4
DISPLAYLIKE'E'.
ELSE.
WRITE/5:BPCODEUSINGNOEDITMASK,
NAME1,STRAS,ORT01,PSTLZ.
ENDIF.
**********************************************

ThetextsymbolscreenisshowninFigure1119.

Figure1119.Program:YCL_CH11_04_LOCAL_IF_CLASS
TextSymbols

ThecustomerinputscreenisshowninFigure1120.

Figure1120.Program:YCL_CH11_04_LOCAL_IF_CLASS
CustomerInput

Thecustomeroutputscreen:

Figure1121.Program:YCL_CH11_04_LOCAL_IF_CLASS
CustomerOutput

Thevendorinputscreen:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

14/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure1122.Program:YCL_CH11_04_LOCAL_IF_CLASS
VendorInput

Thevendoroutputscreen:

Figure1123.Program:YCL_CH11_04_LOCAL_IF_CLASS
VendorOutput

Thescreenforanerrorcondition:

Figure1124.Program:YCL_CH11_04_LOCAL_IF_CLASS
InputErrorCondition

Thiswasanillustrationofgeneralization(businesspartner)and
specialization(businesspartner:customers,andbusinesspartner:
vendors).Polymorphismwasimplementedusinginterfaces.Asimilar
illustrationofpolymorphismusinginheritanceisimplementedinthe
programYCL_CH11_04A_LOCAL_INH_CLASS.Theprogramisnot
listedhere.ItisavailableintheEResource.
HandsonExercise:UseMethodsofSAPDeliveredClass
CL_GUI_FRONTEND_SERVICES
TourofClassCL_GUI_FRONTEND_SERVICES
ThebuiltinclassCL_GUI_FRONTEND_SERVICESoffers
functionalitiesmethodsassociatedwiththepresentationserverorthe
frontend.
Youwillusethefollowingmethodsofthisclassinthecurrentexercise:
FILE_OPEN_DIALOGThismethodenablesaselectionofan
operatingsystemfilelocatedonthepresentationserver.The
methodpresentsadialogueboxwiththefolders/fileslisttoenable
anendusertomakefileselections.Thereisaprovisiontomake
singleormultiplefileselection.
FILE_EXISTThismethodchecksfortheexistenceofagivenfile
onthepresentationserver.Thisisafunctionmethod,andittakes
thefilenameasaninputparameterandreturnsavalueXifthe
fileexistsandblankifthefileisnonexistent.
GUI_DOWNLOADThismethoddownloadsthedataofaninternal
tabletoafileonthepresentationserver.Themaininput
parametersarethefilenameandfiletype(ASCII/BINARY),etc.If
afilealreadyexists,thereisprovisiontooverwrite/appendtothe
existingfile.
Letthesemethodsbeviewedintheclassscreens.
Navigatetotheclassbuilder(SE24),entertheclassname,andclickon
thedisplaybutton.Figure1125willappear.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

15/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure1125.BuiltinClass:CL_GUI_FRONTEND_SERVICES
Methods

Initialmethodsareappearinginblue,andtheyaretheinherited
methodsofthesuperclass:CL_GUI_OBJECT(clickonthePropertiestab
andconfirmthis).Youcanuseonlythemethods,attributes,andevents
withvisibilityPublic.
EnsureyouareontheMethodstab.Clickonthefindmethod/itembutton
(thebuttonwiththearrowmarkinFigure1125).Enter
FILE_OPEN_DIALOGinthefinddialogueboxandpresscontinue
button.Thecursorwillpositiononthemethod:FILE_OPEN_DIALOG,
andthescreenwillappearlikeFigure1126.

Figure1126.Class:CL_GUI_FRONTEND_SERVISESMethod
FILE_OPEN_DIALOG

Whenyouclickontheparameters,youcanviewtheparametersofthis
method.ThescreenfortheparametersofmethodFILE_OPEN_DIALOG
willlooklikeFigure1127.

Figure1127.Class:CL_GUI_FRONTEND_SERVISES
ParametersofMethodFILE_OPEN_DIALOG

NavigatebacktotheMethodstab.Ensurethatyouverticallyscrolledto
thetop,sothatsearchforamethodstartsatthebeginning.Clickonthe
findbutton(underthetabs).EnterthemethodnameFILE_EXISTinthe
dialoguebox,andpresscontinue.Thecursorwillpositiononthemethod
FILE_EXISTasshowninFigure1128.

Figure1128.Class:CL_GUI_FRONTEND_SERVISESMethod
FILE_EXIST

Whenyouclickontheparameters,youcanviewtheparametersofthis
method.ThescreenfortheparametersofmethodFILE_EXISTisshown
inFigure1129.

Figure1129.Class:CL_GUI_FRONTEND_SERVISES
ParametersofMethodFILE_EXIST

Asimilarexercisecanbedoneforlocationandviewingofthemethod
GUI_DOWNLOAD.Thescreensforthemethodanditsparametersare
showninFigures1130and1131.

Figure1130.Class:CL_GUI_FRONTEND_SERVISESMethod
GUI_DOWNLOAD

Figure1131.Class:CL_GUI_FRONTEND_SERVISES
ParametersofMethodGUI_DOWNLOAD

Allofthethreemethods:FILE_OPEN_DIALOG,FILE_EXIST,and

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

16/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

GUI_DOWNLOADarestaticmethods.
ExerciseandABAPProgramSpecifications
ThefunctionalitiesoftheChapter10programYCL_CH10_ILISTS05are
beingextended.Torecapitulate,thisprogramwastakingadatabase
table/viewasinputandlistingoutthefieldsoftheinputdatabase
table/viewwithcheckboxesagainstthefieldsformakingfieldselections.
Theprogramwasretrievingthedataoftheselectedfieldsfromthe
databasetable/viewtooutput.Theprogramwasusingthefeaturesof
runtimedataobjects,fieldsymbols,andOpenSQLspecialconstructsand
interactivelists.
Youwilladdabuttontotheapplicationtoolbaroftheoutputlistofthe
selectedfieldsofaninputdatabasetable/view(firstsecondarylist).
Clickingonthisbuttonwilldownloadthelisttoafileonthepresentation
serverinHTMLformat(intheeventATUSERCOMMAND).
Intheprocessofdownloadingthelisttoafileonthepresentationserver,
youwillbeinvokingthethreemethodsofthebuiltinclass:
CL_GUI_FRONTEND_SERVICES.
Whentheadditionalbuttonontheapplicationtoolbarisclicked,youwill
firstpresenttheuserwithaSelectionScreenpromptingforthefilename.
TheeventATSELECTIONSCREENONVALUEREQUEST...is
triggeredforthisprompttoenabletheusertomakeaselectionofan
existingfileonthepresentationserver.Youareusingthemethod
FILE_OPEN_DIALOGtopresentafileselectiondialogueboxinthe
eventATSELECTIONSCREENONVALUEREQUEST....Theusercan,
ofcourse,makeamanualentryforthefilename.
Aftertheentryofthefilename,whentheuserpressestheexecute
button/functionkeyF8,youwillcheckfortheexistenceofthefileusing
themethodFILE_EXIST.Ifafileisexistent,youarepoppingadialogue
boxforconfirmationoffileoverwritingusingthefunctionmodule
POPUP_TO_CONFIRM.
Ifthefileexistsandoverwritingisconfirmedorthedownloadingfileis
nonexistent,thelist(firstsecondarylist)isconvertedtoHTMLformat
usingthefunctionmodule:WWW_LIST_TO_HTML.Thisfunction
moduletakesasinputthelistnumber(0,1...)andreturnstheHTML
formattedlistintoaninternaltable.
ThisinternaltablecontainingthelistinHTMLformatisdownloadedto
thepresentationserverfileusingthemethodGUI_DOWNLOAD.
Ifthefileexistsandoverwritingisnotconfirmed,amessageisissued
andthesystemremainsonthefirstsecondarylist.
Thefacilityofdownloadingalisttoafileonthepresentationserveris
providedbythesystem(seeFigure1132).Fromanylist,themenupathis
System

List

Save

LocalFile.Thesystempromptsforthefile

format(Figure1133)inwhichthelististobedownloaded:unconverted,
Spreadsheet,Richtextformat,HTMLFormat,andtotheclipboard.

Figure1132.MenuPathforSaving/DownloadingaListtoa
PresentationServerFile

Figure1133.FileFormatSelectionforSaving/DownloadingaList
toaPresentationServerFile

Theideaofprovidingthefacilityalreadyavailableinthesystemthrough

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

17/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

customprogramcodingwouldseeminaneandredundant.Theobjective
hereistodemonstratetheuseofthemethodsoftheclass
CL_GUI_FRONTEND_SERVICES.
ThechangesmadetotheoriginalprogramYCL_CH10_ILISTS05are
markedinthecurrentprogram.
Thesourcecode:

REPORTYCL_CH11_05_USE_GCLASS_FESNOSTANDARDPAGEHEADING.
***********************************************************
*UseMethodsFILE_OPEN_DIALOG,FILE_EXIST,GUI_DOWNLOAD**
*ofClassCL_GUI_FRONTEND_SERVICEStoDownloadFirst**
*SecondaryListinHTMLFormattoaFileonthe**
*PresentationServer/Frontend**
***********************************************************
DATA:BEGINOFFIELDS_STRU,
FIELDNAMETYPEDD03LFIELDNAME,"fieldname
POSITIONTYPEDD03LPOSITION,"fieldpositioninstru1,2..
"lineno.&fieldpositionmap
"onetoone.helpsinaccessing
"afieldwithlineno.
INTTYPETYPEDD03LINTTYPE,"ABAPTYPE:C,D,F,I,N,Petc.
DATATYPETYPEDD03LDATATYPE,"DDICTYPE:CHAR,NUMCetc.
KEYFLAGTYPEDD03LKEYFLAG,"flagforprimarykeyfield
CBOX(1)TYPEC,"fieldenabled/disabledcheckbox
OBLENTYPEI,"widthofoutput
ENDOFFIELDS_STRU,
BEGINOFSFIELDS_STRU,
FIELDNAMETYPEDD03LFIELDNAME,
ENDOFSFIELDS_STRU,
BEGINOFORDERBY_STRU,
FIELDNAMETYPEDD03LFIELDNAME,
ENDOFORDERBY_STRU,
BEGINOFOHEAD_STRU,
FIELDNAMETYPEDD03LFIELDNAME,
OLENTYPEI,"widthofoutput
OTEXTTYPESTRING,
INTTYPETYPEDD03LINTTYPE,
ENDOFOHEAD_STRU,
FIELDS_TABLIKESTANDARDTABLEOFFIELDS_STRU,"allfieldsof
"selectedtable
SFIELDS_TABLIKESTANDARDTABLEOFSFIELDS_STRU,"selectedfieldsof
"selectedtable.used
"inSELECTstatement
ORDERBY_TABLIKESTANDARDTABLEOFORDERBY_STRU,"primarykeyfields
"(insort)
CONDS_TABTYPESTRINGOCCURS0WITHHEADERLINE,"conditionfor
"texttables
OHEAD_TABLIKESTANDARDTABLEOFOHEAD_STRU,"textsfor
"columnheadings
CTRTYPEI,"outputtedfieldnumber
LINSZTYPEI,"LINESIZE
LCNTTYPEI,"temporary
PAGE(3)TYPEC,
CK_BOX(1)TYPEC,"READ..FIELDS_STRUCBOXINTO..
TABCLASSTYPEDD02LTABCLASS,"destinationfieldfromtableDD02L
DSTRUTYPEREFTODATA,"ref.variableofstructureobject
*additioninthisprogramstart*
***********************************
STR_TABTYPEFILETABLEWITHHEADERLINE,"returnselectedfile
HTML_TABTYPESTANDARDTABLEOFW3HTML,"HTMLformattedlist
CNTTYPEI,"nooffilesselectedinfileopendialog
ANS(1)TYPEC,"returnvalueofpopupdialoguebox
CANCEL(1)TYPEC."canceldownload
*additioninthisprogramend*
********************************
FIELDSYMBOLS:<DSTRU>,"fieldsymboltoaccessstructure
<FLD>."fieldsymboltoaccessfield
***********SELECTIONSCREEN***************************
PARAMETERS:TAB_NAMETYPEDD03LTABNAMEVALUECHECK.
ATSELECTIONSCREEN.
SELECTSINGLETABCLASSFROMDD02LINTOTABCLASSWHERETABNAME=TAB_NAME.
IFTABCLASS<>'TRANSP'ANDTABCLASS<>'CLUSTER'AND
TABCLASS<>'POOL'ANDTABCLASS<>'VIEW'.
MESSAGEE022(YCL_CH07_MCLASS01)WITHTAB_NAME.
ENDIF.
***********************************************************
***********************************************************
STARTOFSELECTION.
SELECTFIELDNAMEPOSITIONINTTYPEDATATYPEKEYFLAGFROMDD03L
INTOCORRESPONDINGFIELDSOFTABLEFIELDS_TAB
WHERETABNAME=TAB_NAMEANDFIELDNAMENOTLIKE'.%'AND
FIELDNAMENOTLIKE'/%'.
SORTFIELDS_TABBYPOSITION.
SETPFSTATUS'STAT1'.
SETTITLEBAR'TITLE01'WITHTAB_NAME.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

18/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

*********primarylistlistoffields**********************
LOOPATFIELDS_TABINTOFIELDS_STRU.
WRITE:/5FIELDS_STRUCBOXASCHECKBOX,FIELDS_STRUFIELDNAME.
ENDLOOP.
**************************
*ATUSERCOMMANDevent**
**************************
ATUSERCOMMAND.
CASESYUCOMM.
WHEN'EXIT'.
LEAVESCREEN.
WHEN'BACK'.
SYLSIND=SYLSIND2.
*****************selectall**************
WHEN'SALL'.
LOOPATFIELDS_TABINTOFIELDS_STRU.
MODIFYLINESYTABIXFIELDVALUEFIELDS_STRUCBOXFROM'X'
FIELDS_STRUFIELDNAMEFROMFIELDS_STRUFIELDNAME.
ENDLOOP.
SYLSIND=0.
****************deselectall*************
WHEN'DSALL'.
LOOPATFIELDS_TABINTOFIELDS_STRU.
MODIFYLINESYTABIXFIELDVALUEFIELDS_STRUCBOXFROM''
FIELDS_STRUFIELDNAMEFROMFIELDS_STRUFIELDNAME.
ENDLOOP.
SYLSIND=0.
********************output***************
WHEN'DDATA'.
REFRESH:SFIELDS_TAB,ORDERBY_TAB,OHEAD_TAB,CONDS_TAB.
"initializeinternaltables
LINSZ=0.
CREATEDATADSTRUTYPE(TAB_NAME).
ASSIGNDSTRU>*TO<DSTRU>.
******determineselectedfields,buildinternaltables******
DO.
READLINESYINDEXFIELDVALUEFIELDS_STRUCBOXINTOCK_BOX.
IFSYSUBRC<>0."nomorelinesinthelist
EXIT.
ENDIF.
IFCK_BOX='X'.
READTABLEFIELDS_TABINTOFIELDS_STRUINDEXSYINDEX.
FIELDS_STRUCBOX=CK_BOX.
SFIELDS_STRUFIELDNAME=FIELDS_STRUFIELDNAME.
APPENDSFIELDS_STRUTOSFIELDS_TAB.
ASSIGNCOMPONENTSYINDEXOFSTRUCTURE<DSTRU>TO<FLD>.
PERFORMFILL_OHEAD_TABTABLESOHEAD_TABUSINGTAB_NAME
FIELDS_STRU<FLD>.
MODIFYFIELDS_TABFROMFIELDS_STRUINDEXSYINDEX.
IFFIELDS_STRUKEYFLAG='X'.
ORDERBY_STRUFIELDNAME=FIELDS_STRUFIELDNAME.
APPENDORDERBY_STRUTOORDERBY_TAB.
ENDIF.
IFFIELDS_STRUDATATYPE='LANG'ANDFIELDS_STRUKEYFLAG='X'.
CONCATENATEFIELDS_STRUFIELDNAME'=SYLANGU'INTO
CONDS_TABSEPARATEDBY''.
APPENDCONDS_TABTOCONDS_TAB.
ENDIF.
ELSE.
READTABLEFIELDS_TABINTOFIELDS_STRUINDEXSYINDEX.
FIELDS_STRUCBOX=CK_BOX.
MODIFYFIELDS_TABFROMFIELDS_STRUINDEXSYINDEX.
IFFIELDS_STRUKEYFLAG='X'.
ORDERBY_STRUFIELDNAME=FIELDS_STRUFIELDNAME.
APPENDORDERBY_STRUTOORDERBY_TAB.
ENDIF.
IFFIELDS_STRUDATATYPE='LANG'ANDFIELDS_STRUKEYFLAG='X'.
CONCATENATEFIELDS_STRUFIELDNAME'=SYLANGU'INTO
CONDS_TABSEPARATEDBY''.
APPENDCONDS_TABTOCONDS_TAB.
ENDIF.
ENDIF.
ENDDO.
DESCRIBETABLESFIELDS_TAB.
IFSYTFILL=0."nofieldsselected
MESSAGES023(YCL_CH07_MCLASS01)WITH
TAB_NAMEDISPLAYLIKE'W'.
SYLSIND=SYLSIND1.
EXIT.
ENDIF.
LINSZ=LINSZ+3.
IFLINSZ>1023."SYLINSZCANNOTEXCEED1023.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

19/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

MESSAGES024(YCL_CH07_MCLASS01)WITH
LINSZDISPLAYLIKE'W'.
SYLSIND=SYLSIND1.
EXIT.
ENDIF.
CREATEDATADSTRUTYPE(TAB_NAME).
ASSIGNDSTRU>*TO<DSTRU>.
SETPFSTATUS'STAT2'.
NEWPAGELINESIZELINSZLINECOUNT60."LINSZaspertotalwidth
"ofalloutputtedcolumns
SETTITLEBAR'TITLE02'WITHTAB_NAME.
**************retrievedata&output***********************
SELECT(SFIELDS_TAB)FROM(TAB_NAME)INTOCORRESPONDINGFIELDSOF
<DSTRU>WHERE(CONDS_TAB)ORDERBY(ORDERBY_TAB).
CTR=0.
DO.
ASSIGNCOMPONENTSYINDEXOFSTRUCTURE<DSTRU>TO<FLD>.
IFSYSUBRC<>0.
EXIT.
ENDIF.
READTABLEFIELDS_TABINTOFIELDS_STRUINDEXSYINDEX.
IFFIELDS_STRUCBOX<>'X'.
CONTINUE.
ENDIF.
CTR=CTR+1.
IFCTR=1.
WRITEAT:/5(FIELDS_STRUOBLEN)<FLD>.
ELSE.
WRITEAT:(FIELDS_STRUOBLEN)<FLD>.
ENDIF.
ENDDO.
ENDSELECT.
*additioninthisprogramstart*
***********************************
*********downloadHTML**********
WHEN'DOWNH'.
SYLSIND=SYLSIND1.
SELECTIONSCREENBEGINOFSCREEN2000.
PARAMETERSFILETYPESTRING.
SELECTIONSCREENENDOFSCREEN2000.
CALLSELECTIONSCREEN2000STARTINGAT32ENDINGAT907.
*********************************************************
IFCANCEL='C'."canceldownload
CANCEL=''.
ELSE.
ANS=''.
IFCL_GUI_FRONTEND_SERVICES=>FILE_EXIST(FILE=FILE)='X'.
CALLFUNCTION'POPUP_TO_CONFIRM'
EXPORTING
TEXT_QUESTION='ConfirmOverwriting'(001)
TEXT_BUTTON_1='Yes'(002)
TEXT_BUTTON_2='No'(003)
DEFAULT_BUTTON='2'
DISPLAY_CANCEL_BUTTON=''
START_COLUMN=25
START_ROW=6
IMPORTING
ANSWER=ANS
.
ENDIF.
*********************************************************
IFANS<>'2'.
CALLFUNCTION'WWW_LIST_TO_HTML'
EXPORTING
LIST_INDEX=1
TABLES
HTML=HTML_TAB[].
CALLMETHODCL_GUI_FRONTEND_SERVICES=>GUI_DOWNLOAD
EXPORTING
FILENAME=FILE"'D:\TMP\EEE.HTM'
FILETYPE='BIN'
WRITE_LF='X'
*CONFIRM_OVERWRITE='X'
CHANGING
DATA_TAB=HTML_TAB[]
.
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4.
ENDIF.
ELSE.
MESSAGES038(YCL_CH07_MCLASS01)
WITHFILE."OverwritingExistingFile:&1Cancelled
ENDIF.
ENDIF.
ENDCASE.
*******************************************************
ATSELECTIONSCREENONEXITCOMMAND.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

20/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

CANCEL='C'."forcanceldownload
*******************************************************
ATSELECTIONSCREENONVALUEREQUESTFORFILE.
CALLMETHODCL_GUI_FRONTEND_SERVICES=>FILE_OPEN_DIALOG
EXPORTING
*WINDOW_TITLE=
MULTISELECTION=''
CHANGING
FILE_TABLE=STR_TAB[]
RC=CNT
EXCEPTIONS
FILE_OPEN_DIALOG_FAILED=1
CNTL_ERROR=2
ERROR_NO_GUI=3
NOT_SUPPORTED_BY_GUI=4
others=5
.
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4.
ELSE.
READTABLESTR_TABINDEX1.
IFSTR_TABISNOTINITIAL.
FILE=STR_TAB.
ENDIF.
ENDIF.
*additioninthisprogramend*
********************************
**********************************************************
*headingusingeventTOPOFPAGEDURINGLINESELECTION**
**********************************************************
TOPOFPAGEDURINGLINESELECTION.
LCNT=LINSZ2.
PAGE=SYPAGNO.
WRITEAT/LCNTPAGERIGHTJUSTIFIED.
LCNT=LINSZ4.
WRITEAT/5(LCNT)SYULINE.
LOOPATOHEAD_TABINTOOHEAD_STRU.
IFSYTABIX=1.
IFOHEAD_STRUINTTYPE='F'OROHEAD_STRUINTTYPE='I'
OROHEAD_STRUINTTYPE='P'.
WRITEAT/5(OHEAD_STRUOLEN)OHEAD_STRUOTEXTRIGHTJUSTIFIED.
ELSE.
WRITEAT/5(OHEAD_STRUOLEN)OHEAD_STRUOTEXT.
ENDIF.
ELSE.
IFOHEAD_STRUINTTYPE='F'OROHEAD_STRUINTTYPE='I'
OROHEAD_STRUINTTYPE='P'.
WRITEAT(OHEAD_STRUOLEN)OHEAD_STRUOTEXTRIGHTJUSTIFIED.
ELSE.
WRITEAT(OHEAD_STRUOLEN)OHEAD_STRUOTEXT.
ENDIF.
ENDIF.
ENDLOOP.
WRITEAT/5(LCNT)SYULINE.
SKIP1.
****************************************
*GetColumnHeadingTexts,**
*buildcolumnheadinginternaltable**
****************************************
FORMFILL_OHEAD_TAB
TABLES
OTABLIKEOHEAD_TAB
USING
VALUE(TNAME)
FSTRULIKEFIELDS_STRUVALUE(FLD).
DATA:LNGTTYPEI,
OSTRULIKELINEOFOTAB.
CALLFUNCTION'MG_FIELDNAME_TEXT'
EXPORTING
TABNAME=TNAME
FIELDNAME=FSTRUFIELDNAME
IMPORTING
REPTEXT=OSTRUOTEXT
.
OSTRUFIELDNAME=FSTRUFIELDNAME.
OSTRUINTTYPE=FSTRUINTTYPE.
DESCRIBEFIELDFLDOUTPUTLENGTHOSTRUOLEN.
LNGT=STRLEN(OSTRUOTEXT).
IFLNGT>OSTRUOLEN.
OSTRUOLEN=LNGT.
ENDIF.
FSTRUOBLEN=OSTRUOLEN.
APPENDOSTRUTOOTAB.
LINSZ=LINSZ+OSTRUOLEN+1.
ENDFORM.
***********************************

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

21/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

TheInputscreenwilllikethatinFigure1134.

Figure1134.ProgramYCL_CH11_05_USE_GCLASS_FES:
Input

ThefieldlistwithfieldselectionsisshowninFigure1135.

Figure1135.ProgramYCL_CH11_05_USE_GCLASS_FES:
SelectedFields

TheoutputscreenisshowninFigure1136.

Figure1136.ProgramYCL_CH11_05_USE_GCLASS_FES:
Output

ClickingontheDownloadHTMLbuttonwillpopupthedialogueboxin
Figure1137.

Figure1137.ProgramYCL_CH11_05_USE_GCLASS_FES:
DownloadinHTMLFormat

Enterthefilenameorselectanexistingfile(FunctionkeyF4,etc.).
PressF8/Execute.
Afterthedownloadingprocessisover,thesystemdisplaysamessage
withthenumberofbytestransferred:

Figure1138.ProgramYCL_CH11_05_USE_GCLASS_FES:
DownloadSystemAlert

WhenyouopenthedownloadedHTMLfileinawebbrowser,itwilllook
likeFigure1139.

Figure1139.ProgramYCL_CH11_05_USE_GCLASS_FES:
ContentsofDownloadedFile

Youcandownloadonthesamefileagainandtryortestoutthedialogue
boxforoverwritingfiles.
Therearequiteafewmethodsinthisclass
CL_GUI_FRONTEND_SERVICES.Youcantrythemasexercises.
HandsonExercise:ContextMenusUseMethodofSAP
SuppliedClassCL_CTMENU
ContextMenus
Youcancreateyourowncontextmenu(mouserightclick/shift+F10keys)
usingthemenupainterandtransactioncodeSE41(staticcontextmenu).
Youcanalsocreatecontextmenusandmanipulatestaticcontextmenus
atruntimeusingthemethodsofthebuiltinclass:CL_CTMENU
(dynamiccontextmenus).Thecurrenthandsonexerciseinvolvesthe
creationofastaticcontextmenuandmakingitoperative.
Youarecontinuingwiththeprogramoftheprevioushandsonexercise
andaddingthecustomcontextmenufunctionalitytoitinthecurrent
handsonexercise.Youaredeployingthecustomcontextmenuinthe
firstsecondarylist(i.e.,listofthedataofselectedfieldsofaspecific
databasetable/view).
Bydefault,acontextmenuisavailabletooperateoneveryscreenofa
reportprogram,includingtheSelectionScreens.Withoutacustom
contextmenuinoperation,ifyouclickthemouserightbuttononthefirst
secondarylist(i.e.,listofthedataofselectedfieldsofaspecificdatabase
table/viewofprogramYCL_CH11_05_USE_GCLASS_FES),themenu
optionsavailableareasshowninFigure1140.

Figure1140.ProgramYCL_CH11_05_USE_GCLASS_FES:
DefaultContextMenu

Inthisdefaultcontextmenu,alltheapplicationtoolbarfunctioncode
entriesappear.InthestatusSTAT2,youhadincorporatedtwofunctions
codes:BACKandDOWNH.Thefunctiontextsofthesetwobuttonsare
appearinginthecontextmenu(BackandDownloadHTML).Twoother
optionsHelpandPossibleEntriesareappearinginthecontext
menu.ThecontextmenuoptionPossibleEntriesisnotrelevantinyour
firstsecondarylistcontext.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

22/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

Contextmenuoptionsusefunctioncodesandfunctiontextsonly.
IfyouareCopyingtheprogramYCL_CH11_05_USE_GCLASS_FESonto
theprogramYCL_CH11_06_USE_CL_CTMENU,ensurethatyoucopy
andactivatetheUserinterface.(EnabletheUserinterfacecheckboxin
thecopydialoguebox.)
CreateaContextMenu
Youwillcreateacustomstaticcontextmenuwiththetwofunctioncodes
BACKandDOWNHwiththeircorrespondingfunctiontextsBackand
DownloadHTML.
Tocreateacontextmenu,navigatetothemenupainterwiththe
transactioncodeSE41.Enterthenameoftheprogramas
YCL_CH10_06_USE_CL_CTMENU.Activatetheinterface.
Next,enterthecontextmenustatusnameasSTAT3.Clickonthecreate
button/functionkeyF5.Thescreenpromptforstatustype:Normal
Screen,DialogueBox,orContextMenuwillappear.Entertheshorttext,
selecttheContextMenuradiobutton,andpressthecontinuebuttonas
showninFigure1141.

Figure1141.ProgramYCL_CH11_06_USE_CL_CTMENU:
CreateContextMenu

AscreenwillappearwiththeContextmenubar.Doubleclickonthis
bar.Figure1142willappear.

Figure1142.ProgramYCL_CH11_06_USE_CL_CTMENU:
CreateContextMenu

Asdecidedearlier,youwillenterthetwofunctioncodesBACKand
DOWNHunderthecolumnCode.Pressingthe<enter>keyafter
enteringthefunctioncodewillfetchtherespectivefunctiontexts.The
screenaftertheentryofthefunctioncodeswilllookliketheonein
Figure1143.

Figure1143.ProgramYCL_CH11_06_USE_CL_CTMENU:
ContextMenuEntries

Save,performaconsistencycheck,andactivatethestatusSTAT3.The
contextmenuisreadyfordeploying.
AdjusttheAttributesofFunctionKeySettings(FKeySettings)
Todeployacontextmenu,youneedtoadjusttheattributesofthe
functionkeysettingsofthescreen(normal/dialogue)status.Inthe
presentcontext,thescreenstatuswithwhichyouwanttodeploythe
contextmenuisSTAT2.Sointhemenupainteropeningscreen,enter
theprogram/interfacenameasYCL_CH11_06_USE_CL_CTMENUand
thestatusnameasSTAT2.Clickonthechangebutton/functionkeyF6.
ExpandtheFunctionKeysnode.Thescreenwilllookliketheonein
Figure1142.

Figure1144.ProgramYCL_CH11_06_USE_CL_CTMENU:
StatusSTAT2

Atthebottomofthescreen,thereistheReservedFunctionKeysarea.In
thisarea,positionthecursorinthefieldnexttoShift+F10andpriorto
Contextmenu.Next,selectthefollowingmenupath:Goto

Attributes

FkeysettingasshowninFigure1145.

Figure1145.ProgramYCL_CH11_06_USE_CL_CTMENU:
StatusSTAT2ChangeAttributesofFKeySettings

ChoosingthemenupathwillpopupthedialogueboxinFigure1146.

Figure1146.ProgramYCL_CH11_06_USE_CL_CTMENU:
StatusSTAT2ChangeAttributesofFKeySettings

Inthisdialoguebox,enablethecheckboxListwithContextMenuand
pressthecontinuebutton.Thiswilltakeyoubacktothefunctionkey
settingsnodeasshowninFigure1147.

Figure1147.ProgramYCL_CH11_06_USE_CL_CTMENU:
StatusSTAT2ChangeAttributesofFKeySettings

Thesystemhasenteredthefunctioncode%CTX.Changeittocustom

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

23/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

functioncode.YouhaveenteredMY_CTMENU.Thoughfunctioncode
canbeamaximumoftwentycharacters,thereisaprovisionforten
charactersonly.Thescreenwiththefunctioncodeentered:

Figure1148.ProgramYCL_CH11_06_USE_CL_CTMENU:
StatusSTAT2ChangeAttributesofFKeySettings

SaveandperformaconsistencycheckandactivatethestatusSTAT2.
Thischangingofattributesoffunctionkeysettingsistoindicatethe
deploymentofcustomcontextmenuinsteadofthedefaultcontextmenu.
Youhavetowriteprogramcodeforthecallbacksubroutine
ON_CTMENU_REQUEST.Everytimeauserclicksonthemousesright
buttonorpressesshift+F10,controlwilljumptothissubroutine,and
programcodeinthissubroutinewillbeexecuted.
BuiltinClassCL_CTMENUMethodLOAD_GUI_STATUS
ThebuiltinclassCL_CTMENUhasmethodstoloadstaticcontextmenus,
manipulatethematruntime,andbuildawholecontextmenuatruntime.
YouwillbeusingthestaticmethodLOAD_GUI_STATUStodeployyour
staticcontextmenuSTAT3createdinthemenupainter.Figure1149isa
screenshotofthebuiltinclassCL_CTMENUwiththemethod
LOAD_GUI_STATUSselected.

Figure1149.ClassCL_CTMENU:MethodLOAD_GUI_STATUS

Figure1150showstheparametersofthemethodLOAD_GUI_STATUS.

Figure1150.ClassCL_CTMENU:ParametersofMethod
LOAD_GUI_STATUS

Themethodhasfourimportingparameters.Thefirsttwoimporting
parametersarethenameoftheprogramandthenameofthecontext
menu.Theoptionalthirdimportingparameterprovidesthefunction
codestobedisabled,ifany.ThefourthimportingparameterMENU
mustbeareferencevariablereferringtothebuiltinclassCL_CTMENU.
CallBackSubroutineON_CTMENU_REQEST
Everytimetheuserclicksonthemousesrightbutton,thecontroljumps
tothecallbacksubroutineN_CTMENU_REQUEST(i.e.,thesubroutine
isexecuted).Thesubroutinetakesoneimportingparameter:MENU.
ThisparametershouldbetypedastheclassCL_CTMENU(i.e.,TYPE
REFTOCL_CTMENU).
Thecallbacksubroutinereceivesthereferencetotheinstancetheclass
created.Usingthisformalparameterreferencevariable,youcanusethe
instancemethods,etc.,ofthebuiltinclassCL_CT_MENUwithinthecall
backsubroutine.
Youhavetolocateallthecodeofloading,manipulatingstaticcontext
menustatuses,andbuildingruntimecontextmenusinthecallback
subroutine.
Inthepresentscenarioyouneedtoloadastaticcontextmenustatus.You
areusingthestaticmethodLOAD_GUI_STATUS,alreadydescribedto
deploythecontextmenustatusSTAT3.
TheprogramcodeforthecallbacksubroutineON_CTMENU_REQUEST:
***************************************
*callbackroutineforcontextmenu**
***************************************
FORMON_CTMENU_REQUESTUSINGCT_MENUTYPEREFTOCL_CTMENU.
CALLMETHODCL_CTMENU=>LOAD_GUI_STATUS
EXPORTING
PROGRAM='YCL_CH11_06_USE_CL_CTMENU'"programname
STATUS='STAT3'"contextmenustatusname
MENU=CT_MENU"first/onlyformalparameter
EXCEPTIONS
READ_ERROR=1
others=2
.
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4.
ENDIF.
ENDFORM.

TherestofthecodeofprogramYCL_CH11_06_USE_CL_CTMENUis
thesameasthepreviousprogramYCL_CH11_05_USE_GCLASS_FES.
YouareoperatingthecontextmenustatusSTAT3(shift+F10keys)inthe
firstsecondarylist.Figure1151showsthislistwiththecontextmenu
statusSTAT3inoperation.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

24/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure1151.ProgramYCL_CH11_06_USE_CL_CTMENU:
CustomContextMenu

TheprogramYCL_CH11_06_USE_CL_CTMENUhasbeencopiedto
anotherprogramYCL_CH11_07_USE_CL_CTMENU_V1(copiedwith
interfaceandtheinterfaceactivated).
Inthecallbacksubroutineofthisprogram,theinstancemethodCLEAR
isusedtoinitializethecontextmenu.Withtheexecutionofthismethod,
nocontextmenu(customordefault)willbeoperative.Theclearing
operationisfollowedbytheexecutionofinstancemethodADD
FUNCTION,whichcanaddfunctioncodesandtextstoaruntimecontext
menu.Inthecallbacksubroutineofthisprogramweareaddingjustone
functioncodeandfunctiontext(ADD_FUNCTION)correspondingtothe
applicationtoolbarBackbutton.Thisisademonstrationofbuildinga
runtimecontextmenu.
YoucanfindtheprogramsYCL_CH11_06_USE_CL_CTMENUand
YCL_CH11_07_USE_CL_CTMENU_V1intheEResource.This
concludesthecontextmenucoverage.
ClassBasedExceptionsinABAP
Youhaveraisedexceptionsinfunctionmodules(Chapter7)andmethods
ofclasses(thischapter)usingavariationoftheMESSAGE...statement.
Thetextforthesemessagesiscreatedandmaintainedintransaction
codeSE91andstoredindatabasetableT100.
Youcanraiseexceptionsusingexistingorcustomcreatedexception
classes.Theclassbasedexceptionsaremoreflexible,comprehensive,
andpowerful.Youwillcreateacustomexceptionclassanduseittoraise
exceptionsinanABAPreportprogram,aninternalsubroutine,a
functionmodule,andamethodinaclass.
Therearebuiltinexceptionclassesrelatingtodatabaseoperations,
arithmeticoperations,RFCoperationsetal.Ifyourexceptionraising
requirementsarefulfilledbythese,youmayaswellusethem.Allthe
builtinexceptionclasseshavenamesstartingwithCX_SY.
Youcreateanexceptionclassintheclassbuilder(transactioncodeSE24).
Whilecreatingacustomexceptionclass,youassignitoneofthethree
builtinexceptionclassesasasuperclass.
CreateaCustomExceptionClass(OTRTexts)
Thefollowingthreesuperclassesareusedtocreatecustomexception
classes:
CX_NO_CHECK:
Whenusingthisasasuperclassforyourcustomexceptionclass,youdo
notdeclaretheexceptionswithprocedure(subroutine,functionmodule,
method)interface.Theyareimplicitlydeclaredandpropagated.
CX_STATIC_CHECK:
Whenyoucreateacustomexceptionsubclassofthisclass,exceptions
raisedinaprocedure(subroutine,functionmodule,method)withthe
RAISE...statementareeitherdeclaredintheinterfaceoftheprocedure
orhandledwiththeCATCH...statement.Thereisacompiletimecheck
forthis.
CX_DYNAMIC_CHECK
Withsubclassesofthisclass,exceptionsraisedinaprocedure
(subroutine,functionmodule,method)aredeclaredintheinterfaceofthe
procedure.Thisisnotcheckedatcompiletime,butatthetimeofits
propagation.
Basedonyourscenariocriterion,youchooseoneofthethreebuiltin
exceptionclassasasuperclass.Theseclassescontaintheinterfaceto
maintainmessagetexts,attributes,andtherequiredmethodstoretrieve
theerror/messagetext,etc.Thesethreeclassesare,inturn,subclassesof
thesuperclassCX_ROOT.
Foryourhandsonexercise,youareassigningtheexceptionclass
CX_STATIC_CHECKasasuperclasstoyourcustomexceptionclass
YCX_YCL_CH11_EXCEPTIONS1.
CreateExceptionClassOpeningScreen
Navigatetotheclassbuilder.Thenameofacustomexceptionclassmust
startwitheitherYCXorZCX.Enteranamefortheexceptionclass:
YCX_YCL_CH11_EXCEPTIONS1.
Clickthecreatebutton/functionkeyF5.Figure1152willappear.

Figure1152.CreateExeptionClass

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

25/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

YCX_YCL_CH11_EXCEPTIONS1

TheradiobuttonofExceptionClassisenabled.Youhaveassignedthe
superclassCX_STATIC_CHECK.Ifyouenablethecheckbox:With
MessageClassyoucanusethemessagetextsmaintainedintransaction
codeSE91(databasetableT100).Ifyoudonotenablethischeckbox,you
cancreate/maintainthetextswithintheexceptionclass.ThisisOTR
(OnlineTextRepository)text.Withinanexceptionclass,youcanuse
eitheroneofthese:SE91maintainedtextsortheOTRtexts.Inthe
presentexceptionclass,youwillusetheOTRtexts.
Clickthesavebutton.Thesystemwillpromptforapackage.
CreateExceptionClassAttributesTab
Afterthepackageassignment,thescreeninFigure1153willappear.

Figure1153.ExceptionClassYCX_YCL_CH11_EXCEPTIONS1:
AttributesTab

Youcancreateandmaintainattributes:static,instance,constants.An
exceptionmessagetextmightcontainruntimeinformation.Recallthe
placeholdersinthemessagetextsmaintainedintransactioncodeSE91.
Therewasalimitofamaximumoffourplaceholdersofonemessagetext
maintainedinthetransactioncodeSE91.Intheexceptionclassesusing
theOTRtexts,thereisnolimitonthenumberofplaceholdersfor
runtimeinformationinasingleexceptionIdortextId.Theruntime
informationtobepartofthemessagetextsispassedthroughthe
attributesoftheexceptionclass.
CreateExceptionClassTextsTab
Clickonthetexttab.ThescreenwilllooklikeFigure1154.

Figure1154.ExceptionClassYCX_YCL_CH11_EXCEPTIONS1:
TextsTab

UnderthecolumnExceptionID,youcanentertheexceptiontext
identifiers.(ExceptionIdandTextIdaresynonymous.)Thenamespace
forthesetextidentifiersisamaximumofthirtycharacters.Sticktothe
firstcharacterasalphabetandtherestasalphanumericwithembedded
underscores(_)convention.UnderthecolumnText,youcanenterthe
text.Thereisanoptiontoenterlongtext.(ButtonLongTextoverthe
columnExceptionID.)
Theruntimeinformationinthemessagetextisindicatedbyenclosing
theexceptionclasssattributenameswithinampersands(&).
Forexample,ifyouarereportinganinvalidcustomercode,youcan
createanattributeofnameKUNNRandassignitthedataelementtype
KUNNR.Withinthemessagetext,youwillembedthefollowing
CustomerCode:&KUNNR&Invalid.Beforeissuingthemessage,you
willassignorsettheattributeKUNNR,theinvalidcustomercodeyou
arereportingaserror.Youcanembedanynumberofattributesina
messagetext(i.e.,thereisnolimittotheruntimeinformationinanOTR
messagetext).Theattributesembeddedinmessagetextsmustbedefined
intheexceptionclass.
CreateExceptionClassMethodsTab
Now,clickontheMethodstab.ThescreenwilllooklikeFigure1155.

Figure1155.ExceptionClassYCX_YCL_CH11_EXCEPTIONS1:
MethodsTab

ThemethodsIF_MESSAGE~GET_TEXTand
IF_MESSAGE~GET_LONGTEXTwillbeusedtoretrievetherespective
texts.
UseYourOwnExceptionClassintheEventATSELECTIONSCREENof
anABAPProgram
ErrorScenario:Lettherebeascenarioofraisinganexceptioninan
ABAPprogram.LettwofieldsBUKRS(companycode)andKUNNR
(customercode)inputthroughthePARAMETERS...statement.
Youwillcheckforthepresenceofthecombinationofthevaluesofthese
twoinputfieldsinthedatabasetableKNB1(SELECTSINGLE...).Ifthe
combinationofvaluesenteredisnotavailableinthedatabasetable
KNB1,issuemessage,etc.,youwillreporttheerroneousvaluesofthe
companycodeandcustomercodeasruntimeinformationwiththe
message.
CreateAttributesandTextsforErrorScenario:Lettherequisite
attributesandtextbecreatedinyourexceptionclassforhandlingthis

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

26/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

scenario.
Youwillneedtwoattributesforthetworuntimeinformationtobe
reported.OpentheexceptionclassYCX_YCL_CH11_EXCEPTIONS1in
change/editmode.GettotheAttributestab.Enterthetwoattributesas
showninFigure1156.

Figure1156.ClassYCX_YCL_CH11_EXCEPTIONS1:Attributes
BUKRS&KUNNR

TheattributesBUKRSandKUNNRhavebeenassignedtheTYPES
BUKRSandKUNNR(dataelements),respectively.
ClickontheTextstab,andenterthetextasshowninFigure1157.

Figure1157.ClassYCX_YCL_CH11_EXCEPTIONS1:Exception
IDINVALID_COMB_BUKRS_KUNNR

Saveandactivatetheclass.TheactivationscreenwilllooklikeFigure11
58.

Figure1158.ClassYCX_YCL_CH11_EXCEPTIONS1:Activation

RAISE...StatementSyntax:Anexceptionraisingstatement(usingthe
classbasedexceptions)hasthefollowingsyntax:

RAISEEXCEPTIONTYPE<exceptionname>EXPORTING
TEXTID=<exceptionname>=><ExceptionIDname>
[<attributename1>=<runtimevalue1>..].

TheRAISE...statementshouldbeincludedwithintheTRY&ENDTRY
statementblock.Inyourpresentprogram,youwillbeissuingthe
SELECTSINGLE...statementtoattempttoretrievetherow
correspondingtotheinputvaluesofBUKRSandKUNNR.Following
theSELECTSINGLE...statement,youwillcheckthevalueofthesystem
fieldSYSUBRCandraiseanexceptionifitsvalueisnonzero.
Yourcodesegmentwillbelikethis:
TRY.
SELECTSINGLE<result>FROMKNB1INTO<destination>
WHEREBUKRS=BUKRSANDKUNNR=KEY_KUNNR.
IFSYSUBRC<>0.
RAISEEXCEPTIONTYPEYCX_YCL_CH11_EXCEPTIONS1
EXPORTING
TEXTID=YCX_YCL_CH11_EXCEPTIONS1=>INVALID_COMB_BUKRS_KUNNR
BUKRS=BUKRS
KUNNR=KUNNR_KEY.
ENDIF.
........
ENDTRY.

Inaprocedure(i.e.,asubroutine/functionmodule/method),thiswillbe
theendoftheerrorraisingprocess.IftheRAISE...statementis
executed,theprocedureisexited,theerrorconditionispropagatedor
transmittedtothecallingprogramandwillbehandled,andthen
reportedinthecallingprogramorpropagatedfurther.
Inyourcurrentprogram,aftertrappingtheerror,youwillhavetoreport
theerroraswell.SoyouhaveaCATCH...statementblockforhandling
andreporting.Youwillgetareferencetoyourexceptionclassina
referencevariablewiththeCATCH...statement.Withthisreference
variable,youwillretrievetheerrormessagetextandreporttheerror
withamessagestatement.
FordetailedexplanationofTRYENDTRYandCATCH...statement
blocks,refertotheonlinedocumentation.
SourceProgram:

REPORTYCL_CH11_08_TEST_CBE_ABAP_PG.
***************************************************
*DemoClassBasedExceptionOutsideAProcedure**
***************************************************
DATA:KEY_KUNNRTYPEKUNNR,
ER_REFTYPEREFTOYCX_YCL_CH11_EXCEPTIONS1,
ETEXTTYPESTRING.
*******************************************************
SELECTIONSCREENSKIP4.
SELECTIONSCREENBEGINOFBLOCKBLK1WITHFRAMENOINTERVALS.
PARAMETERS:KUNNRTYPERF02DKUNNR,"combinationofthesetwofields
BUKRSTYPERF02DBUKRS."checkedforinthetableKNB1
SELECTIONSCREENENDOFBLOCKBLK1.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

27/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

*****************************************
ATSELECTIONSCREENONBLOCKBLK1.
IFKUNNRCO'0123456789'"checkallnumeric
KEY_KUNNR=KUNNR+6(10)."adjustforKUNNRlengthbeing16
"instructureRF02Dofallnumericdata
ELSE.
KEY_KUNNR=KUNNR."nonnumericdata
ENDIF.
TRY.
SELECTSINGLEKUNNRBUKRSFROMKNB1INTO(KUNNR,BUKRS)
WHEREKUNNR=KEY_KUNNRANDBUKRS=BUKRS.
IFSYSUBRC<>0.
RAISEEXCEPTIONTYPEYCX_YCL_CH11_EXCEPTIONS1EXPORTING
TEXTID=YCX_YCL_CH11_EXCEPTIONS1=>INVALID_COMB_BUKRS_KUNNR
BUKRS=BUKRSKUNNR=KEY_KUNNR.
ENDIF.
CATCHYCX_YCL_CH11_EXCEPTIONS1INTOER_REF.
ETEXT=ER_REF>IF_MESSAGE~GET_TEXT().
MESSAGEETEXTTYPE'E'.
ENDTRY.
******************************************
STARTOFSELECTION.
WRITE:/5'ValidCombination:',BUKRS,KEY_KUNNR.

ThecombinationofKUNNR=486andBUKRS=3000isinvalid.The
inputofthesevaluesresultsinanexception.Thescreenreportingthe
errorwilllooklikeFigure1159.

Figure1159.Program:CL_CH11_08_TEST_CBE_ABAP_PG
ErrorCondition

UseaCustomClassBasedExceptionintheFunctionModule
ErrorScenario:YouhadcreatedamethodBEAD_STRINGSinthe
customclassYCL_CH11_CL_STRING_OPERATIONS.Youimplemented
thissamelogicinafunctionmodule.Inthemethodofthisclass,youwere
raisinganexceptionusingtheMESSAGE...statementvariation(non
classedbasedexception)ifinputinternaltableortextualarraywas
empty.Inthefunctionmodule,youwillraiseanexceptionusingyour
exceptionclassYCX_YCL_CH11_EXCEPTION1.
Navigatetothefunctionbuilder(transactioncode:SE37),createanew
functiongroupYCL_CH11_TO_DEMO_CBE,andactivateit.Createa
newfunctionmoduleYCL_CH11_FM_TO_DEMO_CBE.Itacceptsthe
textarrayasTABLEsparameter,returningaconcatenatedstingof
individualrowsofthetextarrayseparatedbyaspace.
Theparametersareasfollows:

Figure1160.FunctionModule:YCL_CH11_FM_TO_DEMO_CBE
TablesParameter

Figure1161.FunctionModule:YCL_CH11_FM_TO_DEMO_CBE
ExportParameter

Youareusingaclassbasedexception.ClickontheExceptionstab.There
isacheckboxwiththelegendExceptionClasses.Thishastobeenabledif
youareusingclassbasedexceptions.Inafunctionmodule,youcanuse
eithernonclassedorclassbasedexceptions.Whenyouareusingaclass
basedexception,theexceptionnameyouentershouldexist.Thescreen
withtheexceptionentered:

Figure1162.FunctionModule:YCL_CH11_FM_TO_DEMO_CBE
Exception

Thefunctionmodulesourcecode:

FUNCTIONYCL_CH11_FM_DEMO_CBE.
*"
*"*"LocalInterface:
*"EXPORTING
*"VALUE(RETURN_STR)TYPESTRING
*"TABLES
*"STR_TABTYPESTRING_TABLE
*"RAISING
*"YCX_YCL_CH11_EXCEPTIONS1
*"
DESCRIBETABLESTR_TAB.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

28/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

IFSYTFILL=0.
RAISEEXCEPTIONTYPEYCX_YCL_CH11_EXCEPTIONS1
EXPORTING
TEXTID=YCX_YCL_CH11_EXCEPTIONS1=>NO_DATA.
ENDIF.
LOOPATSTR_TAB.
IFSYTABIX=1.
RETURN_STR=STR_TAB.
ELSE.
CONCATENATERETURN_STRSTR_TABINTORETURN_STR
SEPARATEDBY''.
ENDIF.
ENDLOOP.
ENDFUNCTION.

IntheABAPprogramcallingthisfunctionmodule,itcontainsanoption
toloadthearray(ornot)becauseyourmaininterestisintestingthe
exception,andnotsomuchtheconcatenationprocess.
Thesourceprogramcallingthefunctionmodule:

REPORTYCL_CH11_09_TEST_CBE_IN_FM.
**************************************************
*DemoClassBasedExceptioninFunctionModule**
**************************************************
DATA:TABATYPESTRING_TABLE,
RESULTTYPESTRING,
EXCPTTYPEREFTOYCX_YCL_CH11_EXCEPTIONS1,
ERR_TEXTTYPESTRING.
PARAMETERS:LOAD_DAT(1)TYPECDEFAULT'X'.
STARTOFSELECTION.
IFLOAD_DAT='X'.
SELECTLTXFROMT247INTOTABLETABAWHERESPRAS=SYLANGU.
ENDIF.
TRY.
CALLFUNCTION'YCL_CH11_FM_DEMO_CBE'
IMPORTING
RETURN_STR=RESULT
TABLES
STR_TAB=TABA
.
WRITE:/5'Result:',RESULT."allnonerrorstatements
CATCHYCX_YCL_CH11_EXCEPTIONS1INTOEXCPT.
ERR_TEXT=EXCPT>IF_MESSAGE~GET_TEXT().
MESSAGEERR_TEXTTYPE'S'DISPLAYLIKE'E'.
ENDTRY.

TestingwithLOAD_DAT=''willtriggertheexception.Thescreen
withanerrormessagewilllooklikeFigure1163.

Figure1163.Program:YCL_CH11_09_TEST_CBE_IN_FM
Exception

Thisistheendofthedemonstrationofclassbasedexceptioninafunction
module.
Inasimilarway,youcanuseclassbasedexceptionsinsidemethodsof
classes.Withinaclass,youcaneitheruseclassbasedexceptionsornon
classbasedexceptions.
YoucreatedyourexceptionclassYCX_YCL_CH11_EXCEPTIONS1with
OTRtext.LetanotherexceptionclassYCX_YCL_CH11_EXCEPTIONS2
becreatedthatwilltaketextsthataremaintainedinthetransactioncode
SE91.
CreateaCustomExceptionClass(MessageClassText)
Navigatetotheclassbuilderopeningscreen(transactioncode:SE24),
entertheclassnameasYCX_YCL_CH11_EXCEPTIONS2,andpress
createbutton/functionkeyF5.Intheopeningdialoguebox,enablethe
checkboxwiththelegendWithMessageClassasshowninFigure1164.

Figure1164.ExceptionClass:YCX_YCL_CH11_EXCEPTIONS2

Clickthesavebutton.Theattributescreenispresented.Youcanenter
attributesandfetchSE91texts.
UseaCustomExceptionClassinaSubroutine
ErrorScenario:Youwillhaveasubroutineconcatenatingtherowsofa

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

29/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

textarraysameaswhatyouimplementedinthefunctionmoduleofthe
precedingexample.Youwillraiseanexceptionifaninputinternaltable
ortextarrayisempty.Inthesubroutine,youwillraiseanexception
usingyourexceptionclassYCX_YCL_CH11_EXCEPTIONS2.
Youwilldisplayintheerrormessagethenameofthedataobject(i.e.,the
nameofthetexttableasruntimeinformation).Youaredoingthissoasto
have,attheleast,oneruntimeinformationinyourmessage.Youwill
passtheruntimeinformationthroughanattribute.
Attributes&TextintheExceptionClass:Topasstheruntime
informationofdataobjectname,createanattributeDATA_OBJECTas
Instance,Public,andtypeasSTRINGintheexceptionclass
YCX_YCL_CH11_EXCEPTIONS2.
ClickontheTextstab.Enteranameforthetext(ExceptionID)as
REPORT_NO_DATA.Thescreenwilllooklikethis:

Figure1165.ExceptionClass:YCX_YCL_CH11_EXCEPTIONS2
Text

ClickonthebuttonMessageText.EnterthemessageClassas
YCL_CH07_MCLASS01andthemessagenumberas21.Youcreatedand
usedthismessageinChapter10(InteractiveLists).Youcanusethis
messageforyourpresentpurposes.SelectAttrib.1asDATA_OBJECT
fromthedropdownlist.Thescreenwiththeseenteredvalueswilllook
likeFigure1166.

Figure1166.ExceptionClass:YCX_YCL_CH11_EXCEPTIONS2
TextfromMessageClass

PressontheChange/continuebutton.ThescreenafterreturntoTexts
tabwilllooklikeFigure1167.

Figure1167.ExceptionClass:YCX_YCL_CH11_EXCEPTIONS2
TextfromMessageClass

Save,performaconsistencycheck,andactivatetheclass.
Theclassisusedtoraiseanexceptioninthesubroutineconcatenating
therowsofatexttable.Theexceptionisbeingraisedifthetexttableis
empty.Thesourceprogram:
REPORTYCL_CH11_10_TEST_CBE_IN_SUBR.
*********************************************
*TestClassBasedExceptionInSubroutine**
*********************************************
DATA:TABATYPESTRING_TABLE,
RESULTTYPESTRING,
ERR_REFTYPEREFTOYCX_YCL_CH11_EXCEPTIONS2,
ETEXTTYPESTRING.
*********************************************
PARAMETERS:LOAD_DAT(1)TYPECDEFAULT'X'.
*********************************************
STARTOFSELECTION.
IFLOAD_DAT='X'.
SELECTLTXFROMT247INTOTABLETABA
WHERESPRAS=SYLANGU.
ENDIF.
TRY.
PERFORMCONCATENATERTABLESTABAUSINGRESULT.
WRITE:/5RESULT."nonerrorprocess
CATCHYCX_YCL_CH11_EXCEPTIONS2INTOERR_REF.
ETEXT=ERR_REF>IF_MESSAGE~GET_TEXT().
REPLACEALLOCCURRENCESOF'&'INETEXTWITH''.
"removingtheampersandsfrommessageclasstext
MESSAGEETEXTTYPE'S'DISPLAYLIKE'E'.
ENDTRY.
*********************************************
FORMCONCATENATERTABLESSTR_TABUSINGRESULT
RAISINGYCX_YCL_CH11_EXCEPTIONS2.
"exception/stobespecifiedinsubroutineinterface
DATA:STRTYPELINEOFSTRING_TABLE.
DESCRIBETABLESTR_TAB.
IFSYTFILL=0.
RAISEEXCEPTIONTYPEYCX_YCL_CH11_EXCEPTIONS2
EXPORTING
TEXTID=YCX_YCL_CH11_EXCEPTIONS2=>REPORT_NO_DATA

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

30/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

DATA_OBJECT='TABA'.
ENDIF.
LOOPATSTR_TABINTOSTR.
IFSYTABIX=1.
RESULT=STR.
ELSE.
CONCATENATERESULTSTRINTORESULTSEPARATEDBY''.
ENDIF.
ENDLOOP.
ENDFORM.

ExecutetheprogramwithLOAD_DATequaltoblanktosimulatethe
errorcondition.ThescreenoftheerrorconditionwilllooklikeFigure11
68.

Figure1168.Program:YCL_CH11_10_TEST_CBE_IN_SUBR
ErrorMessage

YoudemonstratedtheclassbasedexceptionsinanexecutableABAP
program,inafunctionmodule,andinasubroutine.Thecoverageof
classbasedexceptionsisover.
ABriefontheABAPRTTS(RuntimeTypeServices)
TheRTTSenablesthecreationofruntimedataobjectsandthe
determinationofattributesofdataobjects.Ithastwocomponents:(1)the
RTTC(runtimetypecreation)and(2)theRTTI(runtimetype
identification).TheRTTCenablesthecreationofruntimedataobjects.
Anditenablesthedeterminationofattributesofdataobjects.
YouhavealreadyusedRTTCinChapter8(FieldSymbols)whereyou
createdaruntimedataobjectusingthestatementCREATEDATA....You
createdaruntimestructurebasedontheinputdatabasetable/view.
Similarlyyoucancreateruntimeelementarydataobjects,runtime
structuredataobjects,andruntimeinternaltabledataobjects.
YouusetheRTTItoascertaintheattributesofdataobjectsinsteadof
usingtheprocedurestatements:DESCRIBEFIELD...,DESCRIBE
TABLE...,etc.,althoughascertainingthenumberofrowsinaninternal
tableatanygivenpointoftimeisnotpossiblewithRTTI.Thiscanbe
easilyachievedbyusingtheDESCRIBETABLE...statementorthe
functionLINES(<itab>).
AhierarchyoftheRTTSclassesandtheirbriefdescriptionscanbefound
intheonlinedocumentation:ABAPSystemClassesandinterfaces
RTTSRuntimeTypeServices.
HandsonExercisetoDemonstrateRTTC&RTTI
Youareusingthefollowingclassesinthehandsonexercise:

CL_ABAP_TYPE_DESCR
CL_ABAP_TABLE_DESCR
CL_ABAP_STRUCT_DESCR

Youinputthenameofadataobject.Thisnameisexpectedtobeaname
ofaglobalorDDICdataobject.Itcanbeatable/flatstructure/view
definition,afieldoftable/flatstructure/viewdefinition,adataelement,
oratabletype(aninternaltabletype).Takecaretoinputavalidnameof
thedataobject.Youarenotperforminganycheckonthisname.An
erroneousnamewillresultinanXdumperror.
Foranelementarydataobject,theprogramisascertainingtheattributes
(a)byfeedingthenameofthedataobjectcontainedinPARAMETERS
variable(byname)(b)byfeedingthefieldsymbolassignedtothedata
object(bydata)and(c)byfeedingthereferencevariablecontainingthe
referencetothedataobject(byreference).Theattributesofthe
elementarydataobjectsuchastype,length,anddecimalsareoutputfor
eachofthethreecases.
Foraninternaltabledataobject,theprogramoutputsthetabletype(A
any,Sstandard,etc.).
Foraflatstructuredataobject,theprogramoutputsthelistoffieldsor
columnsinthestructurewiththeirtypes,lengths,anddecimals.A
DESCRIBE...statementcannotprovidetheseattributesofastructure
(powerofRTTI.)
Youcantryoutthefollowinginputswiththeprogram:

KNA1/LFA1/T001/VBRK/VBRP
KNA1NAME!/T001BUTXT/VBRKNETWR/VBRPFKIMG

Thesourceprogram:

REPORTYCL_CH11_11_ABAP_TYPEDESCRNOSTANDARDPAGEHEADING.
******************************************************************

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

31/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

*UseCL_ABAP_TYPEDESCRtoDetermineTYPE,Length,Decimalsetc.**
*UseCL_ABAP_STRUCTDESCRtoDeterminestructurecomponents**
*UseCL_ABAP_TABLEDESCRtoDetermineInternalTableAttributes**
******************************************************************
TYPEPOOLSABAP.
DATA:ABAP_REFTYPEREFTOCL_ABAP_TYPEDESCR,
STRU_REFTYPEREFTOCL_ABAP_STRUCTDESCR,
TAB_REFTYPEREFTOCL_ABAP_TABLEDESCR,
DREFTYPEREFTODATA,
ABAP_TYPETYPEABAP_BOOL,
FWATYPELINEOFABAP_COMPDESCR_TAB,
STR_TABTYPESTRING_TABLE.
FIELDSYMBOLS:<FS1>.
****************************************************
PARAMETERS:DATA_IT(30)TYPEC
DEFAULT'VBRPNETWR'.
****************************************************
STARTOFSELECTION.
CREATEDATADREFTYPE(DATA_IT)."RTTCdynamiccreationof
"elementarydataobject
ASSIGNDREF>*TO<FS1>."dereferencing
*********elementary:bydata*********
ABAP_REF=CL_ABAP_TYPEDESCR=>DESCRIBE_BY_DATA(<FS1>).
"RTTIcallstaticmethod,getreference/instancegettingcreated
IFABAP_REF>KIND='E'.
"elementarynotstructure,internaltabletype
WRITE:/5'METHOD:DESCRIBE_BY_DATA'.
WRITE:/5'TYPE:',(1)ABAP_REF>TYPE_KIND,"attribute
/5'LENGTH:',(4)ABAP_REF>LENGTHLEFTJUSTIFIED,"attribute
/5'DECIMALS:',(2)ABAP_REF>DECIMALSLEFTJUSTIFIED."attribute
ABAP_TYPE=ABAP_REF>IS_DDIC_TYPE().
WRITE:/5'ISDDICTYPE:',ABAP_TYPE.
********elementary:byname**************
ABAP_REF=CL_ABAP_TYPEDESCR=>DESCRIBE_BY_NAME(DATA_IT).
"RTTIcallstaticmethod,getreference/instancegettingcreated
SKIP2.
WRITE:/5'METHOD:DESCRIBE_BY_NAME'.
WRITE:/5'TYPE:',(1)ABAP_REF>TYPE_KIND,"attribute
/5'LENGTH:',(4)ABAP_REF>LENGTHLEFTJUSTIFIED,"attribute
/5'DECIMALS:',(2)ABAP_REF>DECIMALSLEFTJUSTIFIED."attribute
ABAP_TYPE=ABAP_REF>IS_DDIC_TYPE().
WRITE:/5'ISDDICTYPE:',ABAP_TYPE.
*******elementary:bydatareference***************
ABAP_REF=CL_ABAP_TYPEDESCR=>DESCRIBE_BY_DATA_REF(DREF).
"RTTIcallstaticmethod,getreference/instancegettingcreated
SKIP2.
WRITE:/5'METHOD:DESCRIBE_BY_DATA_REF'.
WRITE:/5'TYPE:',(1)ABAP_REF>TYPE_KIND,"attribute
/5'LENGTH:',(4)ABAP_REF>LENGTHLEFTJUSTIFIED,"attribute
/5'DECIMALS:',(2)ABAP_REF>DECIMALSLEFTJUSTIFIED."attribute
ABAP_TYPE=ABAP_REF>IS_DDIC_TYPE().
SKIP1.
WRITE:/5'ISDDICTYPE:',ABAP_TYPE.
************flatstructure:bydata***************
ELSEIFABAP_REF>TYPE_KIND='u'."structure
ABAP_REF=CL_ABAP_STRUCTDESCR=>DESCRIBE_BY_DATA(<FS1>).
STRU_REF?=ABAP_REF."down/narrowcastingwith?=operator
LOOPATSTRU_REF>COMPONENTSINTOFWA.
WRITE:/5(4)SYTABIX,FWANAME,FWATYPE_KIND,FWALENGTH,
FWADECIMALS.
ENDLOOP.
ELSEIFABAP_REF>TYPE_KIND='h'."internaltable
************internaltable:bydata***************
ABAP_REF=CL_ABAP_TABLEDESCR=>DESCRIBE_BY_DATA(<FS1>).
TAB_REF?=ABAP_REF."down/narrowcastingwith?=operator
WRITE:/5'METHOD:DESCRIBE_BY_DATA_REF'.
WRITE:/5'TABLEKIND:',(1)TAB_REF>TABLE_KIND,"attribute
/5'KEYDEFINED:',(4)TAB_REF>KEY_DEFKIND,"attribute
/5'UNIQUEKEY:',(2)TAB_REF>HAS_UNIQUE_KEY."attribute
ENDIF.

TheoutputoflengthsforcharacterorientedTYPES(C,D,etal.)willbe
equivalenttothelengthsderivedwiththeDESCRIBEFIELD...statement
usingtheINBYTEMODEvariation.Youcanviewtheoutputs.Theinput
andtheoutputsforasampledataobjectareinthefollowingscreenshots:

Figure1169.Program:YCL_CH11_11_ABAP_TYPEDESCR
Input

Figure1170.Program:YCL_CH11_11_ABAP_TYPEDESCR

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

32/33

1/5/2016

Chapter11:ABAPOOPSAPABAP:HandsOnTestProjectswithBusinessScenarios

Outputs

Conclusion
Inthischapter,youwereintroducedtothesyntaxesofclassdefinitions
andimplementations.Youdefinedandimplementedalocalclass.And
youcreatedaglobalclassandusedmethodsofthisglobalclass.
Youdefinedamethodinalocalinterfaceandimplementedtheinterface
methodinlocalclassesanillustrationofpolymorphismusingan
interface.Thereisanotherprograminthesourceprogramresource
illustratingpolymorphismusinginheritance.
YouusedmethodsofthebuiltinclassCL_GUI_FRONTEND_SERVICES
toenhancefunctionalitiesofapreviouslyperformedhandsonexercise
thatlisteddataofruntimespecifiedfieldsofadatabasetable/view.The
databasetable/viewwasalsospecifiedatruntime.Asafurther
enhancementoffunctionality,youcreatedacustomcontextmenuthat
youdeployedinthisprogramusingthebuiltinclassCL_CTMENU.
Youcreatedtwocustomexceptionclassesusingthebuiltinexception
classCX_STATIC_CHECK.Inoneoftheseclasses,youusedOTRtexts,
whileintheotheryouusedtextsmaintainedintransactioncodeSE91.
Youusedthesecustomexceptionclassestohandleerrorconditionsinan
executableABAPprogram,afunctionmodule,andaninternal
subroutine.ThechapterconcludedwithanoverviewofRTTS.
Theclassconceptswillbecarriedforwardtothenexttwochapters(i.e.,
12and13)toproducelistsoroutputsusingthebuiltinclasses.

PREV

Recommended
/ Queue / Recent
Chapter 10: Interactive
Lists / Topics / Tutorials / Settings / Blog / Feedback / Sign Out
2016 Safari.
Terms of Service / Privacy Policy

NEXT

Chapter 12: ABAP List Viewer OutputsPart 1

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch11.xhtml

33/33

Вам также может понравиться