MappingServices 3.0.1 GettingStarted DML AllOS en
MappingServices 3.0.1 GettingStarted DML AllOS en
DML
Version 3.0.1
22 August 2014
Copyright2014Axway
Allrightsreserved.
ThisdocumentationdescribesthefollowingAxwaysoftware:
AxwayMappingServices3 .0.1
Nopartofthispublicationmaybereproduced,transmitted,storedinaretrievalsystem,ortranslatedintoanyhumanor
computerlanguage,inanyformorbyanymeans,electronic,mechanical,magnetic,optical,chemical,manual,orotherwise,
withoutthepriorwrittenpermissionofthecopyrightowner,Axway.
Thisdocument,providedforinformationalpurposesonly,maybesubjecttosignificantmodification.Thedescriptionsand
informationinthisdocumentmaynotnecessarilyaccuratelyrepresentorreflectthecurrentorplannedfunctionsofthis
product.Axwaymaychangethispublication,theproductdescribedherein,orboth.Thesechangeswillbeincorporatedin
newversionsofthisdocument.Axwaydoesnotwarrantthatthisdocumentiserrorfree.
Axwayrecognizestherightsoftheholdersofalltrademarksusedinitspublications.
Thedocumentationmayprovidehyperlinkstothird-partywebsitesoraccesstothird-partycontent.Linksandaccesstothese
sitesareprovidedforyourconvenienceonly.Axwaydoesnotcontrol,endorseorguaranteecontentfoundinsuchsites.
Axwayisnotresponsibleforanycontent,associatedlinks,resourcesorservicesassociatedwithathird-partysite.
Axwayshallnotbeliableforanylossordamageofanysortassociatedwithyouruseofthird-partycontent.
Contents
0 Preface 7
1 Introducing DML 9
Mappingdatainanintegrationengine 9
UnderstandingMappingFlows 11
UnderstandingDMLBlocks 12
ApprovinginputdatawithValidationRules 15
WhatisDML? 15
FoodBrokerproject:Doingthefirststeps 16
CreatingaBusinessDocumentforthecustomerrequest 18
CreatingaBusinessDocumentforthepartner 22
CreatingaBusinessDocumentforbillinganddelivery 24
CreatingaBusinessDocumentforpartnerrates 26
BuildingtheMappingFlow 27
10 Exceptions 129
Makingthingsgowrongyourway 129
Howthesystemhandlesexceptions 130
Eventsandexceptions 130
MappingFlowtransactions 131
Impactofrejectlevelsandexitlocalizations 133
ExceptionsandCustomFunctions 136
FoodBrokerproject:Handlingabsenceofpartnerrates 136
11 Appendices 143
Userestrictions 143
Quick-Reference 144
Definingandreadingtables 144
Messageattributes 148
Workingwithattributesglobally 150
Workingwithattributesondocumentinstances 151
Contextattributes 152
Index 153
Assumed knowledge
Inthisguide,weassumethatyouarefamiliarwiththeB2BorA2Aexchangesandthatyouhave
someknowledgeofAxway5Suite,AxwayIntegratorandAxwayMappingServices.Nospecific
programmingskillsarerequired,butweassumethatyouarefamiliarwithdatamappingconcepts
andtheintegrationengineobjectssuchasBusinessDocumentsorDMLBlocks.
Related documentation
Axway5Suite,AxwayIntegratorandAxwayMappingServicesareeachaccompaniedbyacomplete
setofdocumentation,coveringallaspectsofusingthecomponent.
AllAxwaydocumentationisavailablefromtheSupportwebsite:https://support.axway.com.
FoodBrokerisacompleteprojectofdatamappingforanimaginarybusinessfirm.Thisguidehelps
youtobuildthisprojectstepbystep.Thelastsectionofeachchapterinthisguideisdevotedto
deepeningandenhancingthisFoodBrokerproject.
ExampleFoodBrokerprojectsaredeliveredwithintheAxwayMappingServicesinthedirectory
<MappingServices>\Exercises\Getting started with DML\.Youcanusetheseprojectsasa
basisforyourtestsandtobecomeacquaintedwiththeDML.
Afterhavingcompletedthefirstc hapter,youshouldhaveabetterunderstandingofDML,you
shouldknowwhatstepstofollow,andhowtoconvertyourdatamappingneedsintoaworking
pieceofDMLcode.
Anintegrationengineisasystemthathelpsyouprocessyourbusinessdatawhereveritcomesfrom
andwhateveritsformat,andtosenditontorecipientapplicationswiththedatastructurethey
expect,usingthedesiredtransportmode.Axwayprovidesthefollowingintegrationengines:B2Bi
andAxwayIntegrator.
Toenableanintegrationengineservertoperformsuchcomplextasks:
l Youmusttelltheintegrationengineserverhowthedataisconfiguredandwhatyouexpectto
dowithit.Tocreatethesedescriptions,youusetheGUIcomponentsoftheintegrationengine
inwhichyouconceive,build,andconnectaspecificsetofworkflows.
l DMLisaboutdatamapping.Theprocessofmappingdataisbuildingnewdatawithaspecific
formatfrominputdatathatmightormightnotcomeinadifferentformat.Totelltheintegration
enginehowtoperformsuchatask,youdefineanobjectcalledanIntegrationProcess.
Thefollowinggraphicshowsanintegrationprocess:
IntegrationProcessobjectsareinturncomprisedofoneormoreActivityobjects.Therearevarious
typesofActivityobjectswithdifferentroles,amongwhichyoucannameReceiveActivities,Send
ActivitiesandSequentialActivities.Astheirnamesimply,ReceiveandSendActivitiesarededicated
toexchangingdatawiththeoutsideworld,whileSequentialActivitiesperformdataprocessing.
WithinSequentialActivities,dataisprocessedandmappedbyasub-objectnamedaMappingFlow.
HereisanexampleofaverysimpleMappingFlow:
InMappingFlows,thestructureofdataisdescribedinanintegrationengineobjectnameda
BusinessDocument.Intheprecedinggraphic:
l Datacomesfrominputandisorganized(parsed)totheBD_inputBusinessDocument.
l ThisBusinessDocumentisfedtotheDMLBlocknamedMB_Map.
l TheDMLBlocknamedMB_MapisconfiguredtoextractinformationfromBD_inputand
generatesanewdatastructureasdefinedintheBD_outputBusinessDocument.
l Thisnewdataistransferredtotheout1forforwardingtoanextprocessingsequence.
TheinputandoutputelementsofMappingFlowsprovideconnectionpointstotheActivitiesthat
containtheMappingFlows.ThenetworkofdatapathsdefinedinaMappingFlowcanbevery
complex,involvingseveralBusinessDocumentsandseveralDMLBlocks,asshownschematicallyin
thefollowingpicture:
ThemainideabehindMappingFlowsistospreadcomplexmappingsacrossseveralelementary
processingunits,combiningsimpletaskstomakemorecomplexones.
BeforeprocessingaMainBlock,theintegrationengineserverfeedsallinputswiththeappropriate
data.Thekeyconcepthereisthatinputdataismadeavailablebyaprocessthatisexteriortothe
MainBlock.ThismeansthatwhendefiningtheinternalprocessesoftheMainBlockyoudonotneed
toissueinstructionsfordatacollectionbecausethisisalreadydone.Youonlyneedtodefinewhich
partsofthedatahavetobetopicked-upforthegenerationofoutput.
MainBlocksaresoftwareprogramsthatmapdata,therefore,youhavetoprovideinstructionstotell
themhowtoperformthisaction.Thiscanbedoneinthreeways,dependingonthetypeoftheMain
Block:
WSBlock WebServiceschannel
DBBlock DBchannel
SAPBlock SAPchannel
DMLBlock DMLexpressions
BecausethisguideisdedicatedtoDML,youareconcernedherewithDMLBlocksonly.
DMLBlockscangeneratedatatomultipleoutputs.Eachoutputcarriesdatausingacertainformat
definedintheBusinessDocumentattachedtothisoutput.InstructionsarestructuredinDMLBlocks
aroundtheformatoftheoutput.ForeachoutputBusinessDocument,youdefineasetofruleson
howtobuildthisoutputBusinessDocument.SuchasetofrulesiscalledaMap .
ThefollowinggraphicillustratesaMap:
Asshownintheprecedinggraphic,Mapsarecomposedofindividualorelementaryrules,eachrule
attachedtoaspecificnodeoftheoutputBusinessDocument.EachoftheseindividualrulesisaDML
expressionthatgeneratesthevalueofthenodetowhichitisbound.Suchexpressionsmightpick
updatafromtheavailableinputs,orignoretheinputdataanduseconstantstogenerateoutput
values.
AfteryouhavedefinedasetofMaps,yourDMLBlockknowshowtogeneratedatasuitablefora
specificBusinessDocument.YouthenneedtospecifywhichMapsmightbeusedtoproduce
documentsforthisorthatoutput.YoumakethisspecificationfortheDMLBlockbyusingadditional
objects.
InaDMLBlockyoudefinehowdataisprocessed.Forthisyouhavesomeobjectsavailablewhich
youcancombine.
ForexamplesuchobjectsareConditionslikeDecisionorSwitch,ActionslikeMap,ParseorRouteto
orAdvancedobjectslikeLoop,While,ExitorSet.
ThefollowinggraphicillustrateshowsuchaDMLBlockisdisplayedinAxwayMappingServices:
Asyoucansee,therearesomecombinedobjects.Eachobjectinvokesacertainactionwhichcan
be:
l makingdecisions(If/Then/ElseorSwitch/Casesteps)
l repeatinganaction(LoopandWhilesteps)
l transferringdatafromtheinputstructuretotheoutputstructure(Outputsteps)
l activatingoneoftheMaps(Mapsteps)
Acompletedescriptionofwhatispossibleisbeyondthescopeofthisguide.RefertotheAxway5
Suite,AxwayIntegratorandAxwayMappingServiceso nlinehelpformoredetails.
SimilartoindividualrulesintheMaps,expressionsinValidationRulesproduceavaluethatiseither
yes, the data is eligible,orno, it is not.YoucandefineoneormoreValidationRulesforeach
ofyourBusinessDocuments.ThedocumentisacceptedasaninputonlyifeverydefinedValidation
Rulereturnstrue.
What is DML?
DMLisalanguagethattellstheintegrationengineserverhowtogenerateavaluefrominputdata.It
issimilartoformulasthatyoucanfindincommonspreadsheetsoftware.WithDML,youcanhandle
alltypesofcommondataregardlessoftheirtechnicalencoding:youcancombinenumbers,dates,
andtextstobuildalmostanythingyouneed.
Thislanguagehasbeendesignedasaveryhigh-levellanguage:yourbusinessgeneratesdata
withouthavingtounderstandthetechnicalprocessesbehindthegenerationevents.Thisiswhy
DMLisnottrulyacompleteprogramminglanguage:itisnotconcernedwithbits,bytes,and
memoryallocation.Althoughanexperiencedprogrammerwillrecognizesomeofthestandard
structures,techniquesandvocabularyofprogramminglanguages,DMLexpressionsaremuchmore
similartomathematicalformulasthanrealCorJavacode.
TointroduceFoodBroker,imaginethatyouarecurrentlyworkingfortheInstantTakeOutcompany
whosebusinessistodeliverpreparedmealstocustomersattheirhome.TheInstantTakeOut
companyinvitescustomerstoconnecttotheirwebsite,selectarestaurant,andplaceanorderfor
homedeliveryofmeals.
Thefollowinggraphicillustratesanexamplesoftwaretopologyforthisscenario:
Tomakesuchabusinesswork,youneedtoexchangedatabetweenseveralsoftwarecomponents.
Thesecomponentsmightinvolverecentlyacquiredhardwareandsoftwareaswellaselementsthat
youacquiredandinstalledseveralyearsago.
Inthissituation,processingofincomingordersisneededtoobtaindifferenttypesofdataforboth
ordersforrestaurantsanddeliveriesandbilling applicationinputs.Thisisbecausetheseapplications
acceptdataonlywhenformattedinaspecificway.
InthisFoodBrokersolution,orderprocessingisperformedbyanintegrationengineusingaDML
BlockthatconvertseachXMLdocumentfromthesaleswebserverintotwodifferentoutputXML
documents:the order for restaurantanddelivery and billing data.
First,youneedaBusinessDocumentthatmatchesthisXMLinputfile.TocreatetheBusiness
Documentproceedasfollows:
1. InAxwayMappingServices,intheleft(Project Explorer)frame,callthecontextmenuofthe
subdirectoryBusiness Documentinyourproject.
3. ClickNext andgivethenameofthenewBusinessDocument
Namefield:EnteranameforthenewBusinessDocument.ThisexampleusesBD_
orderFromWebasthename.ClickonFinish,thedocumentwillbecreatedandtheEditor
viewisopened.
4. IntheEditorview,defineacompletesetofBusinessDocumentnodestomatchthestructure
oftheincomingXMLdocument,asinthefollowinggraphic:
5. Checkandsavetheobject.
Asaresult,theXMLdocumentacceptedbythisapplicationasaninputrequiresthreekindof
information:
l Afaxnumber,whichisnotpartofthefaxdocumentbecauseitisdirectlytransmittedtothefax
driver
l Senderandrecipientinformation,whichisusedtofillinthecaptionofthefaxdocument
l Rawtext,whichincludesthedetailsoftheorderandthatconstitutesthebodyofthefinalfax
document
ThefollowingXMLfileisanexampleofinputfortherestaurantorderssoftwarethatmustbe
extractedfromtheXMLinputofthesaleswebserver:
ThesenderisyourInstantTakeOutcompanyandtherecipientistheappropriaterestaurant.The
wholeorderisincludedinthetextbody,withoutprices,butincludingquantities.Thisbodysection
isintheformofrawtext,witheachorderitemonseparatelines.
RepeattheprocedureforcreatingaBusinessDocument,onlythistimenameitBD_
orderToPartner.DefinethestructureoftheBusinessDocumentasshowninfollowinggraphic:
l Composingandprintingtheinvoicesthatarealsousedbytheemployeesofthecompanyas
deliverynotes
l Appendingtheinvoiceinformationtotheaccountingfilesofthecompany
Theinputdocumentforthissoftwareisverysimilartotheorderthatcamefromthewebserver,
exceptthatsomeextraamountsarecomputed:
l Theorderprocessinganddeliveryfees,thatthecustomerischargedwith,thisis5%oftheorder
total
l Thefeespaidbacktothepartnerrestaurant:thisiscomputedfromthepreviousfeesusingarate
thatisrelatedtothepartner
l Thegrandtotaloftheinvoicethatincludesextracustomercharges
PartnerfeescomefromanotherXMLdocumentinwhichpartnernamesarelinkedwiththerate:
Again,repeattheprocedureforcreatinganXMLBusinessDocument,thistimenameitBD_
billingDeliverytomatchthestructureofthisoutputXMLdocumentasshowninthefollowing
graphic:
ThisBusinessDocumentisverysimilartotheBD_orderFromWebBusinessDocument.The
differencesareinthenodeshighlightedinthepreviousgraphic:orderid,amount,charges,
partner_fees,andtotal.EachofthesenodesholdsvaluesthatyourDMLBlockcomputesfrom
thenodesoftheBD_orderFromWebBusinessDocument.
InthisMappingFlow,theinputXMLdocumentistransmittedfromInput1totheMB1_extractor
DMLBlock.MB1_extractorgeneratesafirstXMLdocumentonitspartneroutputandanotherone
onitsbillingoutput.Thesedocumentsarethentransmittedtotheirrespectiveapplications
throughtheMappingFlowoutputspartner_faxandbilling_delivery.
Amorecomplexsolutionisrequiredtoprovidepartnerrates.YourcompanypossessesanXMLfile
containingtherates.TousethecontentofthisfileyoumustaddtwomoreDMLBlockstothe
MappingFlow:MB_tableLoaderandMB_tableBuilder.
Inthisnewprocessingsequence,thestarteventactivatestheMB_tableLoaderthatloadsthe
partnerfileandplacestherawtextofthefileinthefollowingBusinessDocument:
TherawdatanodeoftheMB_rawTableBusinessDocumentcancontainbinaryrawdataand
receivesthewholetextofthefile.ThetaskoftheMB_tableLoaderDMLBlockistoloadthefile
usingservicesoftheoperatingsystemdirectly.ThisDMLBlockknowswherethefileliesandhowto
loaditwithoutthehelpoftheintegrationengineparsingservices.Dataisreadfromthediskand
placedwithoutchangesintherawdatanode.
ThisBD_rawTabledocumentisthenprocessedbytheMB_tableBuilderDMLBlockwhich
generatestheBD_partnerRatesBusinessDocument.
ThetwoinputsoftheMB2_extractorDMLBlockarefedwiththeweborderandthepartnerrates
table,andthendataforthetwoexternalapplicationsisgenerated.
Inthefollowingchapters,youwilllearnhowtodefinetheMappingFlowsinordertodocumentdata
andmakethewholesystemoperational.
Afterhavingreadthischapter,youwillknowaboutthetypesofdatayoucanmanipulateinDML
expressionsandhowtostateliteralvalues.Youwillhaveabasicknowledgeoftheuseofvariables
andnamingconventions.
About expressions
Intheprevioussectionsofthisguide,youhaveseenbasicexamplesinwhichbitsoftextperformed
controlormappingofdata.ADMLexpressionisoneofthosebitsoftext.Thewholepurposeofan
expressionistomaketheintegrationenginebehaveinacertainway.
Expressionsarecomposedofstatements.Expressionsmustfollowaveryprecisesyntax,otherwise
yourexpressionwillberejected.Forexample,amongtheprimaryrulesofsyntaxistherequireduse
ofthesemicolon;toseparatestatementsfromeachother.
Statementstelltheintegrationengineservertoperformsomeelementarytasks.Variousactionscan
beperformedinstatements;theverbsthatstatethoseactionsarecalledinstructionsoroperators.
InstructionsandoperatorsareEnglishwordsthathavespecialmeaningsinDMLexpressions.They
arethereservedkeywordsofthelanguage;thismeansthatyoucannotusethosewordsoutside
theirspecificpurpose.
AnexampleofDMLinanexpressionisthissimplemathematicalcomputation:
Thisexpressiontellstheintegrationenginetoadd89to1992andthentomultiplytheresultsby
78.9.Themeaningisabsolutelythesameasinconventionalmathexpressions.Noticetheuseof
reservedcharacters(,),+and*asarithmeticalsymbolsforpriority,addition,andmultiplication.
Inthisexample,theresultvaluethatisgeneratedis:164190.9.MostDMLexpressionsgeneratea
valuethatisusedbytheintegrationengineaseithertheresultofdatacheck,ortofillnodesof
outputdata.
ThisiswhyexpressionsareboundtoBusinessDocumentsorBusinessDocumentnodes.Thevalue
generatedbyaValidationRuleofaBusinessDocumentstateswhethertheinputdocumenthasbeen
successfullycheckedornot.ValuesgeneratedbyMapsareusedbytheintegrationengineserverto
fillthecorrespondingnodesintheoutputBusinessDocument.
Instructionsandoperatorsactonobjectsasshowninthenumbersinthepreviousexample.Those
numbersareamongthemostprimitiveobjectyoucanseeinexpressions:literals.Morecomplex
objectsdoexistintheintegrationengine;thesearereferredtousingtheirnames.
ThefollowingisthelistofDMLreservedkeywordsandcharacters.
( ) { } [ ]
; , + - / &
:= = <> \ \\ ..
* : $ in out <
@@ % ! {# #} **
xor
Using literals
TherearethreeliteraltypesinDMLexpressions:numbers,strings,anddates.Eachofthesehasa
specificsyntax.
NumbersarequotedusingtheusualEnglishsyntaxofnumbers:decimaldigitsandfullstopdecimal
separator.Althoughnotveryreadableforhumanbeings,digitscannotbegroupedwhenusinglarge
numbers:2,147,483,648isnotlegalinexpressions,only2147483648isaccepted.Leading
andtailingzeros,whennotsignificant,canbeomittedornot:000.31416,0.31416,
0.3141600and.31416arealllegalandrefertothesamevalue.
Ascientificnotationwithexponentandsignificandisalsoaccepted.TheEnotationisusedsince
superscriptisnotconvenienttotypein.Onlyzerosignificandsarelegal.Thismeansforexample
thattheAvogadronumber6.022141510 23isonlyacceptedintheform.60221415E24,while
6.0221415E23isrejectedassyntaxerror.
Evenifyournumbersarerelatedwithquantitieswithunits:amountofmoney,volumeofbeerYou
shouldneverquotethoseunitsinliterals:apint(imperial)is568.26125 ml,butyoushoulduse
only568.26125inexpressions.
StringsarethebasicunitoftextinDML,unlikeinsomeotherprogramminglanguages,evenasingle
letterisrepresentedasaone-letterstring.Youcanplacealmostanycharacterinstringsthatyoucan
typein,includingreservedcharactersandnon-romancharacters,ifyourkeyboardallowsthat.
TopreventtheDMLinterpreterfromrecognizingreservedwordsinstringliterals,youmustsurround
thetextwithdoublequotes"".Herearesomesamples:
Anirritatingcharacteristicofthequotesisthattheyarenotspecialcharactersthatappearonlyin
computerprograms.TheyareapartofanynormalEnglishtexttoindicateemphasisorthat
someonehasspoken.Thequotesinaliteralstringhaveadifferentmeaningthanthequotesthat
surroundtheliteral.
Sincethereisonlyonekeyonyourkeyboardtomakeaquote,youcanuseatechniquethatiscalled
escaping .Inmostcomputerlanguages,atleastonecharacter,calledanescapecharacter,is
designatedtohavethepowertoremovethespecialsignificancefromotherspecialcharacters,such
asquotes.InDML,thischaracteristhebackslash(\).
Topreventtheintegrationengineserverfromthinkingthatithasprematurelyreachedtheendof
yourstring,youneedtoescapethequotesinyourstringsasshowninthefollowingexample:
InDMLyoucanusethefollowingescapesinstringliterals:
\" fordoublequote(")
\\ forrealbackslash(\)
\t fortabulationcharacter
\r forcarriage-returncharacter(ASCII0x0D)
\n forline-feedcharacter(ASCII0x0A),notthenewline.
Theremainingtypeofliteralyoucanuseinexpressionsisadate-and-timeliteral,usuallynamed
dateliterals.Thisliteralisusedtorefertoaspecialmomentintime;eitherjustadayintheyear,ora
precisemomentofthatday.
Dateliteralsarealwayssurroundedbysinglequotes(')andarestrictlyformatted.Twovariationsare
possiblefollowingadateandatimeisstated,oronlyadate.
l Ifyouwanttostatethelastdayof20 th century,use:
'2000-12-31'(December31 st,2000)
l Fortheveryfirstsecondofthe21 stcentury,use:
'2001-01- 00::01'
l Minutesandsecondscanbeomitted,sonoonof2006Christmasdayis:
'2006-12-25 12'
l Tenpastnoonon2006Christmasdayis:
'2006-12-25 12:10'
l Dateliteralscanbe(optionally)augmentedwithfractionsofsecondsasinthefollowing
meaning1msbeforeChristmas:
'2006-12-24 23:59:.9999'
Thedecimalfractionshallhavefromonetoninedigitsafterthefullstopseparatormakingtheliteral
atleast1nsprecise.
DatesandtimesexpressedbytheseliteralsaresupposedtobeGMT(orUTC)timesorbaretimes
wherethetimezoneisnotsignificant.Youmightalsostatethetimezoneifrequired,letsconsider
noonofIndependenceDayinNYC:
'2006-07-04 12:00:-04'
Evenifsomepartsofthedatecanbeomitted(minutes,seconds,andtimezone),leadingzerosare
alwaysrequired:7:23 AMisalwayswritten 07:23.
Naming objects
Severalobjectsthatdoexistintheintegrationenginecanbeusedinexpressions:variables,input
documents,user-defined-functions,andtables.
Manyoftheseobjectsaresourcesofdata.Themainpurposeofthelanguageistogeneratedata
fromotherdata,eithertocontroltheinputortomaketheoutput.
WhenusingAxwayMappingServices,alltheavailableobjectsarecategorizedinentitiesandfolders
andeachhasaname.Ifyouwanttorefertooneoftheseobjectsinanexpression,youusethat
tripletknownasfullyqualifiedname.Somecharactersareusedtoseparatethesethreepartsofa
name:
myentity.myrootfolder\onesubfolder\anotherone.myobject
Namesarecomposedoflettersonly(eithercapitalornot),digits,andtheunderscoresign(_).But,
ifyouvedefinedanobjectnamed0695,youmustsurrounditsnamebyexclamationmarksin
expressions.InDMLexpressions,theobject0695isreferredtoas!0695!.Thosemarksare
requiredforeverynamethatstartswithareservedkeywordorincludesareservedcharacter.
Entitiesandfolderscanbeomitted;thesameobjectcanbenamed:
1. myentity.myrootfolder\onesubfolder\anotherone.myobject
2. myrootfolder\onesubfolder\anotherone.myobjectorevenjust:
3. myobject
Whentheintegrationengineserverdetectsashortenedname,itcompletesthenametoafullname
usingthecurrentcontext.Thismeansthatthemissingentityandfoldersareimplicitlythoseofthe
objecttowhichtheexpressionisbound.
WhendealingwithaValidationRule,implicitentityandfoldersarethoseoftheBusinessDocument
towhichtheconstraintisbound.WhendealingwithaDecision-PathoraMap,theboundDML
Blockisused.
Folderscangroupnotonlyobjects,butalsootherfolderssoyoucancreateacompletehierarchyof
folderstocategorizeyourobjects.Whenyouspecifythefoldersinaname,youmuststateallthe
foldersandsubfoldersseparatedbyareverseslash.However,youcanomittheveryfirstfolderin
thefolderhierarchy.Inthatcase,youmustjustomittherootfoldernameasinthefollowing
example:
\onesubfolder\anotherone.myobject
Inmostcases,youuserawnamestorefertoobjectsinexpressions.Therearetwoexceptionstothis
situation:variablenamesandpathstoinputBusinessDocumentnodes.
Forvariablenames,apercentsymbol(%)isalwaysusedtointroducethename:
%myvariable
or,fullyqualified:
%myentity.folder1\folder2.myvariable
AlltheaspectsofpathstoBusinessDocumentnodesareexaminedlaterinthisdocument.
Handling data
Computersingeneral,andcomputerlanguagesspecifically,segregateeverythingtheydealinto
types.Typesarecategoriesofthingswithwhichtheexpressionwillwork.Whenathinghasatype,
theintegrationengineserverknowshowtobehavewiththatthing.
Thisisafundamentalaspectofhowtheintegrationengineworks.Withoutanamedtypeforthe
abstractideasthattheyworkwith,theintegrationengineserversdonotknow,howtotechnically
carryoutbasicthingssuchascombiningtwodifferentvalues.However,ifyouhavetwothings,and
theyareofthesametype,rulesexistforcombiningormappingthem.
SixtypesofthingsareavailableinDMLexpressions.Theycoverallthedatathattheintegration
enginedealswith.Inthislanguage,typesarecalledclasses.
l Boolean
Booleantypeisusedfordatathatrepresenttruth.Imagineyouaredealingwithanelectronic
invoicethatstateswhetherithasbeenpaidornot.Thatinformation(paidornotpaid)is
typicallystoredinaBooleandatanode.Booleansarebasicallynumbers,restrictedtothe{0,1}
setforfalseandtrue.Forconvenience,reservedwordstrueandfalsecanbeusedin
expressionstorepresentBooleanliteralvaluestrue(1)andfalse(0).
ThistypeisalsoreferredtoasclassB.
l Integer
Integertypeincludesallthepositivenaturalnumbers,theirnegatives,andzero.Unsimilarto
mostofthecomputerlanguages,nodifferenceismadebetweenshortandlongintegers.The
integrationengineservercancomputenumberswithatmost18significantdigits(technically
64-bitintegers).
ThistypeisalsoreferredtoasclassI.
l Real
Thistypeistheoneforfloating-pointnumbers.Inessence,thespecialdistinctionbetweenareal
andanintegeris,thatarealhasacomponentthatisafractionof1.Numberssuchas1.01,
2.34,0.02324,andanyothernumberthatcontainsafractionalcomponentistreatedasa
floating-pointnumber.Thisisthetypethatyouwouldwanttousefordealingwithmoneyor
withthingsdealtwithinpartialquantities,similartogasolineorpairsofsocks.
ThistypeisalsoreferredtoasclassR.
l String
Thistypeisfortextdata.Stringscanincludeasmanyascharactersneeded:limitedonlyby
computermemoryexhaustion.Theintegrationengineservercanhandleanyexistingcharacter,
manyencodingschemasaresupported.Mostofthetime,youdonothavetoconsiderthe
technicalaspectsofencodingstringswhenusingtheminexpressions.
ThistypeisalsoreferredtoasclassS.
l Date
Thedateclassisthetypeforsingledatesorcompletetimelandmarks.Theintegrationengine
servercanhandlesdatesintherangeofOctober15 th ,1582toDecember31 st,9999.Thistypeis
alsoreferredtoasclassD.
l Raw data
Rawdataclassisthetypededicatedtoreceiveamountofrawdatawithnospecificsignification
andnolimitinsize.Itcanbeseenasanarrayofbytes.ThistypeisalsoreferredtoasclassV.
DatacomputedinDMLexpressionscanhaveregularvaluesorsymbolicvalues.
Regularvaluesaretheusualvaluesfortheclassofthedata.Forexample,.6022E23isaregular
valueforclassR."Quick brown fox over lazy dog"isaregularvalueofclassSandfalseisa
regularvalueforclassB.
Twosymbolicvaluesareavailableforanydataofanyclass:nullandabsent.Thenullvalue
representsvaluesthatareimpossible,suchastheresultofdivisionbyzeroorgettingthelogarithm
ofanegativereal.Theabsentvalueisforemptydata.Imagineanelectronicreceiptwhichincludes
afieldforatelephonenumber:thefieldisnotoptionalsothat,ifnovalueisavailable,theabsent
symbolicvaluehastobeusedinplaceofavalue.
Evenifclassessegregatedatafromeachother,bridgesexisttomapdatabetweendifferenttypes.
Thismechanismiscalledimplicitconversion.Theproblemariseswhenyouwanttocombinevalues
ofdifferentclasses,asinthefollowingexpression:
5 * 3.1416 + 28
ThisexpressiondealswithclassRandclassInumbers.Forthecalculationsexecutedbyhuman
beings,thisisnotaproblem.Butforacomputer,realnumberscannotbemultiplieddirectlywith
integers:5(classI)hastobemappedin5.0(classR)andthenyieldsaresultthatisclassR.
InDMLexpressions,thismechanismiskepthiddenfromyou:theintegrationengineserverisclever
enoughtoautomaticallydecidetoconvert5(I)into5.0(R).Notallconversionsarepossible,the
followinggraphicshowswhichconversionsarepossibleandwhicharenot.
Thearrowsshowimplicitconversionsthattheintegrationengineservercanperform.Implicit
conversionsalwaysmapdataofaspecializedclassintodataofamoregeneralclass.Forinstance,
realnumbersareageneralizationofintegernumbersjustasafruitisageneralizationoforange,
mango,bananaandmanymore.Thisiswhyimplicitconversionsarealsocalledpromotions.
Kindsoftransitiveoperationscanalsobepreformed:whenrequired,theintegrationenginecan
directlymaptheBooleanvaluetrueintothestring".1e+1".Firsttrueisturnedintointeger-type
number1,thenintoreal-typenumber1.0thatisfinallyconvertedintostring".1e+1".
Variablesactsimilartostoragebins.AftercreatedusingAxwayMappingServices,youcanfillyour
variableswithdata,andlaterretrievethemsoyoucanputdifferentdataintothatvariable.Although
variablescanstoreonlyonepieceofdataatatime,youcanreusethemoverandoveragaintostore
differentinformation.Theircontentsmightvaryfromtimetotime,hencethenamevariable.
Ifyouknowthatyourexpressionsneedtotemporarilystoredata,youmustfirstcreateenough
variablestostorethem.ThisoperationisdoneintheAxwayMappingServiceswhereyoudefinethe
nameandtheclassofeachofyourvariables.VariablesthatyoudefinecanbeusedinanyDML
expression.
YouuseDMLtomapdatathattheintegrationenginehandles.Thisdataisalwaysstructuredin
messages.Eachtimeanewmessagecomestobeprocessed,thevalueofeachexistingvariableis
restoredtoitsinitialcontents.WhenyoucreateavariableinAxwayMappingServices,youdefinean
initializationexpressionthatcomputestheinitialcontent.
Atanytime,inanyexpression,youcanalterthecontentsofavariable.Thisoperationiscalled
assignment.Assignmentstatementsrelyonthespecificoperator:=.Hereisanexampleofthe
assignmentoperation:
%avogadro_number := .60221415E24
Thestatementabovestorestherealnumber6.022141510 23inavariablenamedavogadro_
number.Theleadingpercent%isthereservedcharactertointroducethenamesofvariables.This
assignmentisonlyacceptediftheclassofthevariableisRorS:intheformercaseanumberis
stored;inthelateritisfirstconvertedintoastringandthenstored.
Anyliteralcanbeassignedtovariable,providedthattheclassesarecompatible:
%favorite_sentence := "the quick brown fox jumps over the lazy dog"
%mybirthday := '1964-05-29'
%days_in_year := 365
%concept_understood := true
%mms_in_inches := 2.54
Raw-dataliteralsdonotexist,soraw-data(Vclass)variablescannotbeassignedinthisway.
Assigningvariablesmeansalteringtheirvalue,buthowdoyouretrievetheircontents?Yousimply
usetheirnameaspartofanexpression.Theareaofacircleisgivenbytheformula:S = r2
Toperformthiscalculation,youneedthreevariablesofRclass:onetoreceivetheareaofthecircle,
onethatcontainsthevalueofpi,andoneforthecircleradius.Mappingtheexpressionswouldbe:
%pi :=3.1415926535;
%radius := 135;
%area := %pi * %radius * %radius
Thisexpressionsetsthevalueofthevariableareato57255.5261116739.
Variablesarevisiblefromanyexpressionyoucanwrite;theircontentisrestoredtotheinitialvalue
onlywhenanewmessageiscapturedbytheintegrationengineserver.Sincetheircontentis
preservedfromexpressiontoexpression,theyofferaneasywaytoshareinformationbetweenthe
differentcomponentsofyourMaps:
ThisgraphicshowshowakeyparameteroftheMapissharedbetweentheDMLBlocksandthe
ValidationRules.
Thisexampleusestheimplicitmethod:itsvalueis%height * %area.Thevalueofanexpression
isimplicitlysetbyitslaststatement.Thisiscorrectonlywhenthelaststatementgeneratesavalue:
multiplicationdoes,assignmentdoesnot.
Tospecifyexplicitly,usethereservedcharacter$thatreferstotheexpressionvalue.Writing$ := 4
inanexpressionmeansitsactualvalueis4.
ThefollowingisasimpleexercisetodefinethebasicMappingFlowwiththeMB_extractorDML
BlockandtheXML-header-fillingsectionofaMap.
Intheproject,theMB_extractorDMLBlockisusedtogeneratetwooutputs.Youneedtodefine
andactivatetwoseparateMapstofillthesetwodifferentdocuments.
2. FollowthewizardandgivethebasicpropertiesforthenewMap.
l Filename:MR_webToPartner
l Next
l SelectInput Business Document BD_orderFromWeb.bdoc
l SelectOutput Business Document BD_orderToPartner.bdoc
l Finish
l ThenewMapwillbecreatedandtheEditorviewisopened.
3. IntheEditorview,beginenteringtheexpressionsthatconvertdatafrominputtooutput
nodes.
Forthemoment,enterexpressionsforonlytwonodesintheXMLheader.Thesenodeshold
constantsthatspecifytheXMLversionanddocumentencoding:
4. Intheexpressionfieldfor:
XmlVersionnode,enter"1.0"
XmlEncodingnode,enter"ISO-8859-1"
Thisisthesimplestuseofexpressions:Youenterthestringliteralsthatyouwanttoinputtothe
correspondingnode.
5. Usingthesamemethod,defineasecondMapthatgeneratesdataforthebillingsystemand
routestheinputdocumenttothebillingoutputoftheDMLBlock.
Thistime,includeavariation:Placethevaluesfortheversionandencodingnodesin
variables.
DefinetherequiredvariablesbyusingthecontextmenuontheExtended Objectsdirectory.
6. InthefollowingwizardgivethenameofthevariableandFinish.Aftercreatingthevariable
doubleclickonthenewobjectversion.var andenterthevalueofthevariableintotheopened
editingview.
7. Repeatthisfortheencoding.
8. Afteritisdefined,thevariablesnamedversionandencodingdisplayintheResource
navigationpanelundertheVariablescategory.YoucannowusethemtofilltheXMLheader
oftheMB_billingDeliveryBusinessDocumentwithintheMR_webToBillingMap,asinthe
followingexample:
Noticethevariablesintheexpressionfieldsofnode2(XmlVersion)andnode3map
(XmlEncoding).Expressionsareelementary:justthenamesofthevariablesintroducedbythe
reservedcharacterpercent.
Creating the Mapping Flow that process the data through the developed
Business Documents and Maps
1. CreateanewMappingFlowandnameitordertoPartner:
Leftside:Resource view
Upperrightside:Editorviewwithpanelviewontheright
Bottomrightside:Propertiesview,otherviewscanbedisplayedifneeded
2. FromthepanelputaBusinessDocumentintotheeditorselect BD_orderFromWeb.bdocand
connectitwiththeinput.
3. PutaDMLBlockintotheeditorandnameitMB1_extractor.
4. IntothisDMLBlockputtwoMaps.SelectthetwoMaps,createdbefore.
5. AddtwooutputsandtwomoreBusinessDocumentsintotheeditor.FortheBusiness
DocumentsselecttheDocumentsBD_orderToPartner.bdocandBD_billingDelivery.bdoc
andthanconnectthemwithanoutput.
6. AfterthatconnecttheBD_orderFromWeb.bdocwiththeMB1_extractorandtheMapwith
thecorrespondingBusinessDocumentsfromtheoutputside.
Inthischapter,youreturntotheuseofnumbersandsomeofthewaysinwhichDMLworkswith
them,includingbasicarithmeticandmoreadvancedfunctions.Thecommonpitfallsofusing
numbersintheintegrationengineenvironmentareincluded.
Whenyouhavefinishedthischapter,youwillbefamiliarwiththebasiccategoriesofnumbersthat
DMLuses,andwiththeoperatorsandbuilt-infunctionsforusingthem.
Additionandsubtractionareperformedusingtheoperators+and-.Adding500 to340,andthen
subtracting10 looksasfollows:
500 + 340 - 10
Inadditionto+and-,multiplicationisperformedbytheasterisk*,anddivisionbytheforward
slash/.Prioritiesofoperatorsfollowthestandardmathematicalrules:multiplicativeoperationsare
alwaysperformedfirst,mappingtheexpressioncomputesthevalue410andnot800:
40 * 10 + 10
Asinstandardmathematics,youcanchangetheprioritiesusingparenthesistogrouptheoperations
tobedonefirst.Thefollowingexampleresultsin800:
40 * (10 + 10)
Thelastoperatorfornumbersistheexponentiation(orpower)operatorthatraisesitsleftoperand
tothepowerofitsright,doubleasterisk**isused:
2 ** 3 8
-3 ** 2 -9
(-3) ** 2 9
2 ** -2 0
2.5 ** 2 6.25
2.0 ** -2 0.25
Noticethattheexponentiationoperatoroperatesonlywithpowersthatarewholenumbers:you
receiveanerrorifyouenter2**2.5.
Thisoperatorbehavesdifferentlywhenraisingwholenumbersorfloatingpointnumberstonegative
exponents:whenyouwrite2 ** -2youintendtogenerateawholenumber,youreceive0
becausetheactualvalueof2 -2is.
Noticealsothatthepoweroperatorbindstighterthantheunaryminus,so-3**2isinfactthesame
as(3**2).Ifyouwanttocalculate(-3),youmuststateitexplicitlyusingtheappropriate
parenthesis.
3 * .98242E-5 + 568.35 / 59
Becarefulwhendealingwithexpressionsthatmixintegerandrealnumbers,orthatusedivision.
Theseoperationsmightnotbeasstraightforwardasyouwouldexpectbecauseofthedistinction
betweenfloating-pointnumbersandwholenumbers.
Whencomputingnumberoperations,theintegrationenginefirsttriestodeterminethenature(the
class)oftheresult.Whenoperandshavethesameclass,theintegrationenginechoosesthatclass
fortheresults.Thismeansthataddingwholenumbersresultsinawholenumberandadding
floating-pointnumbersresultsinfloatingpointnumbers.
Thisbehaviormightleadtopuzzlingresults,forexampletheexpression2/3iscomputedasan
operationbetweenwholenumbers,resultinginthewholenumber0.Whereas,intheexpression
2.0/3.0,literalsaredetectedasfloating-pointnumbers,leadingtothevalue0.66666
Whenoperandsdifferinclasses,classRisalwayschosenfortheresult.Thismeans,thatthe
expression2 / 3.0isevaluatedas0.66666since3.0isrecognizedofbeingaclassRvalue.
Ifyouwantyourexpressiontobehaveasyouexpect,youmustcarefullychoosethewayyouwrite
numberliterals:3.0doesnothavethesameeffectas3.Keepinmindtheimportanceoftheclasses
ofthevariablesyouuse.
Symbolic values
Similartoanyotherdata,numbersintheintegrationenginecanhaveoneofthetwosymbolic
valuesnullorabsent.
Thesevaluesabsorbothervalueswhenusingbasicmathoperators.Thismeansthatwhateverthe
operatoris(+,-,*or/),theresultingvaluewillbenullasshowninthefollowingexamples:
Becarefulwhenwritingexpressionsthatmightperformsuchacalculation:unlikelythatyouwill
obtainthecorrectvalue.Furthermore,noerrorisgeneratedconcerningtheprecisionerror.
Time arithmetic
Inadditiontocombiningnumbers,addition,andsubtraction,operatorscanoperateontimevalues.
Withtheseextensions,youcanperformtimeshiftsorcomputedurations.
Thepitfallhereisthattheeffectiveoperationperformeddependsonthenature(classes)ofthe
operands:shouldbothbeofclassDandtheresultsofthesubtractionisaninteger,shouldtheleft
beofclassDandtherightofclassIandtheresultisofclassD.
Considerthefollowingexpressions:
'2000-12-31' + 1
'2001-01-02' 1
'2000-04-01 16:14' - '2000-03-30 16:15'
Thefirstandsecondexpressionsbothperformtimeshifts:theformercomputesthedateoftheday
aftertheDecember 31 st, 2000,thelatercomputesthedateofthedaybeforeJanuary 2 nd ,
Timeshiftsarecomputedusingcompletedaysandalldateandtimecomplexityishandled.For
example:
while
Thelastexpressioncombinestwodatestocomputethenumberofcompletedayselapsedbetween
thetwooperands,thatexpressionevaluatesto1:only47hoursand59minuteselapsedbetween
thetwodates,thatisenoughforonedaybutnotfortwo.
Shiftingorcomputingdurationusingdaysisusuallyenough.Butundercertaincircumstances,one
mightappreciatetodealwithseconds,minutes,hours,monthsoreitheryears.Thiscanbe
accomplishedwiththe+andoperatorsassociatedwithoneaccuracyspecifier.Fiveaccuracy
specifiersareavailableinDML,theseare:
s second
m minute
h hour
M month
Y year
Thesespecifiersareattachedtothestandardoperatorstochangetheiraccuracy.Thefollowing
expressionsperformtimeshiftsusingunitsofmonths,yearsorhours:
'2000-12-31' +M 1'2001-01-31'
'2001-01-02 08:54' -Y 1'2000-01-02 08:54'
'2000-04-01 16:14' +h 15 '2000-04-01 07:14'
Timeshiftsusingseconds,hours,ordaysalwaysevaluatetoanexistingdateintheGregorian
calendar.ShiftingtothedayafterFebruary28 th mightevaluatetoeitherFebruary28 th orMarch1 st.
Timeshiftsusingmonthsbehavedifferently.Whenyoushiftonemonthinthefutureyouobtainthe
samedayinthenextmonth:fromDecember14 th toJanuary14 th .Monthshiftsoperateregardless
oftheexactcountofdayselapsed:shiftingonemonthmightresultsin28,29,30or31daysshift.
Inaddition,monthshiftsfromdatesafterthe28 th ofamonthnevercrossmonthends.Shouldthe
resultingdatenotavaliddateintheGregoriancalendar(suchasJune31 st),itisadjustedtothelast
dayofthemonth.Youcouldsaythatendsofmonthsarestickywhencomputingtimeshifts.
Thefollowingaresomeexamples:
Yearsshiftsalwaysevaluatetothesamedayinanotheryear,regardlessthenumberofdayselapsed:
fromJuly 14 th, 2007toJuly 14 th, 1789.Shiftingoneyearmightresultineither365or366
daysshifts.IftheobtaineddateisaFebruary 29 ththatdoesnotexist,itisadjustedtoFebruary
28 thasanapplicationofthestickyendofmonthparadigm.
Whencomputingdurations,thespecifierschangetheunitoftheresultingvalue.Forexample,you
canobtainthetimeelapsedbetweenSeptember 17 th, 2008 8:54andSeptember 18 th,
2008 8:55inseconds,hours,months,oryears,asfollows:
Theobtainedvaluecanbethenumberofseconds,minutes,hours,ordayscompletelyelapsed
betweenthetwodates.Fordurationsinmonthsandyears,thevalueobtainedisthebiggest
possibleshiftoftherightoperandthatgeneratesadateanteriortotheleftoperand.Thismethod
ensuresconsistencywiththewaymonthsshiftsareprocessed.
Function Description
abs Computestheabsolutevalueofitsargument.
OperatesbothonclassRandIargument,thevaluereturnedhasthe
sameclassasthefunctionargument.
remainder Computestheremainderofadivisionofwholenumbers.
round Turnsafloating-pointnumberintoawholenumberusingtheusual
roundingtechnique(2.1becomes2and2.78becomes3).
OperatesonlyonclassRandalwaysreturnsaclassIvalue.
ceil Returnsthelowestintegerwhichisstillgreaterthantheargument.
OperatesonclassRandreturnsaclassIvalue.
floor Returnsthehighestintegerwhichisstilllowerthan
theargument.
OperatesonclassRandreturnsaclassIvalue.
integerPortion Returnsintegerpartofaspecifiedfloating-pointnumber.
OperatesonlyonclassRandalwaysreturnclassI.
decimalPortion Returnsdecimalpartofaspecifiedfloating-pointnumber.
OperatesonlyonclassRandalwaysreturnclassI.
TodeterminetheorderID,useaverysimpletechnique:Thecurrentdateandtimearemappedtoa
wholenumbervalueasshowninthefollowingexpression:
1000000*dayOfYear(%now) + 10000*getHours(%now)
+ 100*getMinutes(%now) + getSeconds(%now)
Inthiscase,built-infunctionsareusedtoextractthecomponentsofthedatefromthevariable
now.Youmustdefinethisvariable,settingtheinitialvaluetothecurrentdate.Todothis,invoke
theGetDateAndTime()function.Sincevariablesareresetateachnewincomingmessage,eachID
isdifferent.
Awholenumbervalueisthencomputedusingbuilt-infunctionsthatextractpartsofthedate.Ifthis
expressionisevaluatedat19:34:32on2007,October13 rd ,thereturnedIDwouldbe:
289193432.
Createthevariablenowandfillitwiththeexpressionasyoucanseeinthefollowingpicture:
EntertheaboveexpressionintheMR_webToBillingMapyoudefinedpreviously.Youassociate
theexpressionwiththeorderidnodeasillustratedinthefollowinggraphic:
Inthischapter,youwilllearnhowtocomputecomplexstringsfromseparateparts.Aquicktourof
theusefulthingsyoucandowithbuilt-instringfunctions,suchassplitting,padding,extracting
andsoon,isincluded.
Thischapterisintendedasanoverviewofwhatyoucandowithstrings.Onlythemainstring
manipulatingfunctionsarepresentedhere.Foradditionalinformationonstringmanipulationwith
DMLrefertotheDMLUserGuideandDMLReferenceGuide.
Themostbasicstringoperationiscalledconcatenation.Concatenationisforstringswhatadditionis
fornumbers.Whenyouwritesomethingsimilartothefollowing,youinstructtheintegrationengine
tobuildanewclassSvaluebymergingthethreestringliteralsleading,middleandtailing:
Theresultingvalueis:"leadingmiddletailing"
Youcanconcatenatestringstoanysizeyouneedwithinthelimitsofavailablememory.ClassS
valueshavenomaximalstructuralsize.Youcanplacetexttheequivalentofonethousandtimesthe
contentsoftheBibleinasingleSclassvariablewithoutoverflowing.
Asmultiplicationistherepletionofnumbers,youcanrepeatconcatenationusingamultiplicationof
somekind.Whenyouwritethefollowingstring,youtelltheintegrationenginetoconcatenate
leadingthreetimesandmiddletwiceandappendthelatterattheendoftheformer:
3 * "leading" + "middle" * 2
Theresultingvalueis:"leadingleadingleadingmiddlemiddle"
Thistypeofoperationiscalledexternalmultiplication. Youcombineoperandsofdifferentnatures
(astringandawholenumber)tocreateanewstring.Theexternalelementinthiscaseisthewhole
number.Multiplying,evenexternally,isperformedbeforeadding.
Oneofthesefunctionsisthelengthfunctionthatcomputesthenumberofcharactersinagiven
string.Forexample:
Inthisexample,thelengthofthestringis35characters,includingspacesandthefinalexclamation
point.Thefunctionreturnsawholenumber(classIvalue)andcountsallthecharacters,including
leadingandtailingspaces.
Considerasecondexample:
Thisexpressionalsoreturnstheresult35.Leadingandtrailingspacesarecounted.Thecharacter
countsasasinglecharacterevenifitseemstobecomposedofanaandane.
Whenusingthelengthfunction,onlysinglecharactersarecounted,howeveryouenterthem(
countsforone,evenifyouuseeand^onyourkeyboardtoenterit),thenumberofglyphstheyre
composedof,orthewaytheyaretechnicallyencoded(aisencodedonfourbyteswhenUCS32is
used,butcountsonlyforonecharacter).
SpecialfunctionsareincludedinDMLtoaccomplishsuchtasks.Theseare:trimString,
trimStringLeft andtrimStringRight.Thesethreefunctionscreatenewstringsratherthan
changingthecontentsofthesuppliedones.Thefollowingareexamplesofvaluesreturnedbythese
threefunctions(greycolorisusedtodisplayspaces):
Asyoucansee,leadingspacesareremovedbytrimmingandtrimStringLeftwherethetrailing
spacesareremovedbybothtrimStringandtrimStringRight.Spacesincludedwithinthetextare
notremoved.
Thetrimfunctionsoperateonlyonstrings.Theyarenotlimitedinremovingspaces.Youcanuse
theiroptionalsecondargumenttoremoveanythingthatisundesirableinyourstrings:
Sometimes,youmightwanttoinsertspacestomakeyourstringconformtoacertainformat.Thisis
quitecommonwhendealingwithdocumentswhereinformationiscolumnar.Unsimilartotrimming,
onlytwofunctionsdopadding:
Intheseexamples,threespacesareeitherinsertedatthebeginningorappendedattheendofthe
originalstringtomakeanewone.Inbothcases,thefinallengthincreasesfromeighttoeleven.
l inalllowercase
l INALLUPPERCASE(WHICHCANBECONVEYEDASSHOUTING)
l asamixofUPPERCASEandlowercaseletters,toemphasize
Toconverteverycharacterinastringtolowercase,usethefunctiontoLower,whereasfor
uppercaseconversion,usetoUpper.Similartotrimmingandpaddingfunctions,thesefunctions
generatenewstringswithcharacterschangedratherthanmodifytheoriginalones.
ThesefunctionsoperateasexpectedonlyonstringsencodedusingASCII-lineagecharactersets:
ISO646,ISO8851andallUnicodeUTFs.
Youcanusethefollowingfunctionstoextractpartsofaspecifiedstring:
l getStringLeft(string, count)
Thisgeneratesanewstringvaluethatincludesonlythefirstcountcharactersofstring.
l getStringRight(string, count)
Thiscreatesanewstringvaluethatcontainsonlythecountendingcharactersofstring.
l getSubString(string, start-index, count)
Thisextractsthepartofthestringstringthatstartsatstart-indexth characterandiscountlong.
Herearesomeexamples:
Whenspecifyingcountorstart-index,alwaysusepositivewholenumbers(classI)toavoidreceiving
nullvaluesorerrors.
Specifyinginappropriateclassesforarguments(stringmustbeimplicitlyconvertibletoclassS,and
countandstart-indextoclassI)leadstoobfuscatederror:
Usingnegativevaluesforcountorstart-indexalwaysleadtonullvalue.Sodoesusingastart-index
thatisplacedaftertheendofthestring,forexamplegreaterthanthestringlength.Forstart-index,
rememberthatthefirstcharacterofthestringis1.
Replacing parts
Twofunctionsareavailablewhichenableyoutosearchforasubstringinastringandreplaceitby
anotherone.Theseare:replaceString andreplaceStringAll.Theformeroperatesonlyonthe
firstoccurrencewhilethelaterreplacesall.
Example
Inbothcases,theoriginalstringisreturnedverbatimifthesearchpatternhasnotbeenfound.
Usethecontentofthenowvariable,butthistimeitisprocessedasastringviaimplicitconversion
frominteger:
TheresultsofthecalltogetHoursisconvertedtoastringbecauseitisconcatenatedtoanother
string.Tomatchtheresultsofthepreviouschapter,hours,minutes,andsecondsneedtoalwaysbe
twodigitslong.Toaccomplishthis,twoleadingzerosareaddedtoeachresultandthentheresult
stringiscuttoalengthoftwocharacters.
EntertheaboveexpressionintheExpressionfieldoftheorderidnodeintheMR_
webToPartnerMap.
InthisBusinessDocument,thesenderinformationisalwaysthesameandiswrittentothenodevia
stringliterals:
ThischapterdescribesoneofthemostcomplexaspectsofDML:pathstoBusinessDocuments
nodes.Youwillconsidereverythingfrombasicpathstocomplexpathsthatselectonlyspecificparts
ofaBusinessDocument.
Intheintegrationengine,theprocessingsequencethatdefinesanintegrationisdefinedinan
integrationprocess.Tomaketheindividualpiecesofdataofaninputmessageavailablefor
handling,theintegrationengineparsesthedatatoaBusinessDocumentinstance.Business
Documentsareformaldescriptionsofthewaythedataoftheinputmessageisstructured.
ABusinessDocumentdescribesthedatacarriedandmappedintheintegrationenginefroma
hierarchicalpointofview:BusinessDocumentsarecomposedofnodes.Eachnodeeitherholdsdata
orgroupsasubsetofnodes.NodesinBusinessDocumentsarenamed,butthesenamesdonothave
tobeuniqueinaBusinessDocument.
AgivennodeofaBusinessDocumentcanbeoptional,multipleormandatory.Inadditiontoa
name,eachnodehasapropertycalledcardinalitythatstatesthenumberoftimesthenodecan
occur.Therearefourpossiblecardinalities:
l 0..1
Thenodecanoccuratthemostonetime;
thisisanoptionalnode:canoccurorbeomitted.
l 1..
Thenodeoccursonetime,nomorenorless;
thisisamandatorynode,cannotbeomitted.
l 1..n
Thenodemustoccuratleastonetime;
thisnodeismandatorybutcanhavemultipleoccurrences.
l 0..n
Thenodecanbeomittedoroccuratleastonetime;
thisnodeisoptionalandcanhavemultipleoccurrences.
Itiseasytoimaginetheuseofoptionalnodes:youmightreceiveinvoicesinwhichsome
informationiscriticalandsomeoptional.Forexample,invoicesinwhichthebilledamountis
neededbutnotnecessarilythecustomer'sbirthdate.
Anodemightoccurmorethanonetimeincaseoflists.Consideramailaddress.Itusuallyconsists
ofoneormorelinescontainingtheexactlocation(streetnumber,streetname,floor..),azipcode
andacityname.
Forthezipcodeandcitynamethisisnoproblem,youjustdefinetwonodesnamedzip_codeand
city_name.Itismorecomplicatedfortheaddresslines.Youcanchoosetodefinethreenodes
line_1,line_2andline_3thateachholdsoneofyourlines.
Thismethodcanbeawkward:youmightreceiveemptylines,andwhenanewrecordarrives,you
mighthavetoappendline_xxnodestoholdmorelengthyaddresses.Whatisactuallybehindyour
collectionofline_xxnodesisalist.Intheintegrationengine,youprepareforthisvariedinputby
definingauniquenodenamedlineswith1..ncardinalitywhichindicatesthatthisisalistofdata
withoneormoreitems.
Elementary paths
IfyouwanttousethedataofaBusinessDocumentinDMLexpressions,youhavetoprovideits
location.BusinessDocumentsarecomplexdatastructureswithseveralcompoundlevelsofnodes.
ToidentifythelocationofanelementofdatainaninputBusinessDocument,youmustgivethe
completeaddressofthenodethatholdsthatelement.
ThecompleteaddressofaBusinessDocumentnodeiscalledthepathtothatnode.
Apathiscomposedofthenamesoftheintermediatenodesthatyoumustpassthroughtoreach
yourgoal.Consideramailaddressincludedinaninvoice.Topositivelyindicatethecityname
containedintheaddress,youmightneedthefollowingpath:
Apathiscomposedofthenameofthec ity.
IfyouwanttousethatcitynameinaDMLexpression,youwritethepathusingthereserved
character\toseparatenodenames:
\invoice\customer\address\city
Thereservedcharacter\isnotaseparatorbutarealconnectorthatmeansmemberof.Thismeans
thatwhenyouusea\b,youmeanthenodenamedbthatisadirectmemberofthegroupnode
nameda.Intheabovepath,theleading\meansthatinvoicenodeisdirectlyincludedattheroot
oftheBusinessDocument.
Suchpathscanbeverylongifyourdocumentiswellstructuredandcontainslotsofinformation.In
thisexample,youmightneedaquickerpath,similartothenodecitythatisincludedininvoice
groupnode.Insuchasituation,youcanuse\\toconnectcitytoinvoicemeaningnodesincluded
directlyorthroughanytreeofnodes.
Thefollowingpathaddresses,withashortcut,allthenodesnamedcitythatareincludedinthe
supergroupinvoiceregardlessofintermediatelevels:
\invoice\\city
Reservedpatterns\and\\areknownasrelationshipconnectorsinDML.
Justasinthepathstofilesonyourdesktopcomputer,youcanuse..toaddressthenodethat
groupsanotherone.Reusingyourcityexample,thefollowingpathaddressesthenodecustomer:
\invoice\\address\..\customer
Youcanusethisparentoperatoranywhereinapath,providedyoudonotendapathwith(..)and
addressanodethatactuallyexists.Thevirtuesof (..)aredescribedlaterinthisguide.
ABusinessDocumentcanholdvariouskindsofdatathatarefedtotheintegrationengineusing
severalformats.OnekindofBusinessDocumentistheXMLBusinessDocument.Someextra
propertiesexistforBusinessDocumentnodesthatareXML-specific.
WhencreatingaBusinessDocumentofXMLtype,youcancreatenodesforXMLattributes.These
arecalledattributenodesandareaddressedusingthe@specifier.IfthisinvoiceisheldinanXML
documentwherethecitynameisanattribute,thepathtothatcitynamewouldbeasfollows:
\invoice\customer\address\@city
AnXMLBusinessDocumentcanalsocontainchoice,sequenceandallnodes.Thesearecontainer
nodesthatarenotpartofnodeaddresses.Therefore,theirnamesareneverincludedinnodepaths.
Makingcustomernodeeitherachoice,asequenceoranallnodechangesthepathtocityname
into:
\invoice\address\@city
WhenspecifyingtherulesforbuildingtheoutputsofaDMLBlock,youcanpickdatafromanyof
theinputBusinessDocuments.DMLBlockscanhandlemultipleinputs.Thisfeatureimpactsnode
paths:theinputusedispartofthenodeaddress.
Apaththatincludesaninputlookssimilartothefollowingpathwherethecolonseparatestheinput
BusinessDocumentnamemy_inputfromtherestofthepath:
my_input:\invoice\customer\address\city
Specifyingtheinputisoptional:whenomitted,theinputisdeducedfromthecontext.For
ValidationRules,youcanonlyaccesstheBusinessDocumenttowhichtheexpressionisbound.
Pathsmustnotstateanyinput.InMaps,thefirstinputdefinedintheDMLBlockisimplicitlyused.
Ambiguous paths
Reviewthefollowingpaththatusesthedouble-backslashconnector\\toabbreviatenodepaths:
\invoice\\city
Thisindicates,withashortcut,allthenodesnamedcitythatareincludedinthesupergroup
invoice,whateverintermediatelevelstheremightbe.
Nowconsiderthecasewhereinvoicesalsocontaintheaddressofasupplier.Theabbreviatedpath
addressesbothofthefollowing:
\invoice\customer\address\city
\invoice\supplier\address\city
SuchapathiscalledanambiguouspathbecauseitaddressesmorethanonenodeintheBusiness
Document.Inthissituation,the\\connectorisresponsiblefortheambiguitybecauseitspecifies
allthenodeswithinasub-tree.
Ambiguouspathscanbeverypowerfulbecausetheyareawaytoperformcomplexoperationsusing
verynaturalandsimpleexpressions.
Suchpathscannotbeusedeverywhereinexpressions:DMLdoesnothavethecapacitytoperform
arithmeticwithmatrices.Expressionssuchas\\a + \\barenotlegalifoneofthepathsis
ambiguous.
invoice 1..1
line 1..n
item_id 1..1, class s
quantity 1..1, class i
unit_price 1..1, class r
amount 1..1, class r
customer 1..1
name 1..1, class s
address 1..1
lines 1..n, class s
zip_code 1..1, class s
city_name 1..1, class s
discount_code 1..1, class i
id 0..1, class s
Theamountnodeiscomputedfromunitpriceandquantityusingasimplemultiplication.The
expressionthatfillsthenode\invoice\line\amountis:
\invoice\line\unit_price * \invoice\line\quantity
Theproblemisthatnodelineismultiple,sobothpathsintheaboveexpressionaddressmorethan
oneoccurrence,morethanonedataelement.Performingsuchamultiplicationonmorethanone
valueisbeyondthecapacitiesoftheintegrationengine.Thisexpressionwillberejectedwithapath
cardinalityerror.
Paths,similartonodes,havetheirowncardinalitythatrestrictstheiruseinexpressions.Each
individualnodethatisincludedinthepathimpactsthecardinalityofthewholepath.The
integrationenginecomputesthepathcardinalitybyexaminingeachnode.Ifanoptionalnodeis
encountered,thepathisconsideredasoptional;ifamultiplenodeisencountered,thepathis
consideredasmultiple.Usingthepreviousexample,youcanexhibitpathswithdifferent
cardinalities:
l \invoice\line\quantity
ismultiple-mandatory(1..n)becausebothinvoiceandquantityaremandatorywhereasline
ismultiple.
l \invoice\customer\name
ismandatory(1..1)becauseallitscomponentsaremandatory(1..1).
l \invoice\customer\id
isoptional(0..1)becausealthoughinvoiceandcustomerare1..1,idisoptional.
Inmostsituations,expressionscannotcontainpathswithmultipleoroptionalcardinalities(either
0..1,0..nor1..n).ChapterHandlingmultipleoccurrencesonpage91describeswhatcanbedone
withsuchpaths.
Ifyouwanttousethequantityofthefirstinvoiceline,thebracketspecifierhasbeenincludedin
DMLforsuchasituation.Youcanselectoneoccurrenceofamultipleoroptionalnodeusingthat
specifier.Forexample,thefollowingaddressesthequantitynodeofthefirstoccurrenceofline:
\invoice\line[1]\quantity
Thespecifierhasturnedtheoriginal1..npath\invoice\line\quantityintoa1..1onebecause
youhaveselectedonlyoneoccurrenceoflineamongthepotentialones.
Thebracketspecifiercanbeusedonanynode,evenonthosethatare1..1.Betweenthebracketsis
aclassIvaluethatspecifiestheoccurrenceindex,startingatone.Thatvaluecanbeanylegal
expression.Theindexcanbecomputedcombiningliterals,variablevaluesorvaluesfromnodesof
anyinputdocument.Forexample:
\invoice\line[1]\quantity
* \invoice\line[1]\price
* in2:\discount[\invoice\customer\discount_code]\rate
Thelineamountiscomputedfromquantityandunitprice,asexpected.Aspecialdiscountrateis
alsousedthatcomesfromanotherBusinessDocumentoninputin2.Thislaterdocumentcontainsa
discountrateslistthroughmultiplenodediscount.Thecorrectoccurrenceofdiscount(thecorrect
iteminthelist)isselectedusingthediscountcodeastheoccurrenceindex.
TheonlyrequirementabouttheindexvalueconcernsitscompatibilitywithclassI.Atthetimeyou
checktheexpressioninAxwayMappingServices,nospecificcontrolisdoneaboutthevaluebeing
inaspecifiedrange.Thisisbecausethenumberofoccurrencesisknownonlyatthetimedatais
beingprocessed.
If,byaccidentordeliberately,theindexvalueismorethanthenumberofoccurrences,orlessthan
one,thepathwouldaddresssomethingthatdoesnotexist.Asaresult,thevaluewouldbeabsent.
Ifyourinvoicecontainsonlyonelinewhereitemquantityis345:
\invoice\line[1]\quantity referstoanoccurrencethatexists,valueis345
\invoice\line[2]\quantity doesnotrefertosomethingthatexists,valueis
absent
IntheexampleofaDMLBlockthatcomputestheamountsininvoices,nodiscountrateindexis
suppliedwithintheinvoiceitself.Discountratesarestatedinalistthatcontainsratessidebyside
withthecustomernames.ThisistheBusinessDocumentthatholdsthelist:
discount 1..n
name 1..1, class s
rate 1..1, class r
Tocomputethefinalamount,youneedtheunitprice,thequantity,andtheratethatisapplicable
tothecustomerwhoshouldreceivetheinvoice.Youneedtosearchamongoccurrencesof
discountforaspecificvalueofnameandretrievetherelatedrate.
Thewaytodothisinpathstoanodeisnamedwhereclauses.Whereclausesselectasubsetof
occurrencesofanodeusingasuppliedcondition.Theexpressiontocomputeyourinvoiceamount
(forline1)isasfollows:
\invoice\line[1]\quantity
* \invoice\line[1]\price
* in2:\discount[where item\name = \invoice\customer\name]\rate[1]
Whatisimportantisthe[where]partofthepathtorate.Thisparttellstheintegrationengineto
retrieveoccurrencesofnodediscountthatmatchthecondition.
Heretheconditionstatesthatthecustomernamethatresidesintheinvoice(path
\invoice\customer\name)shouldbeequaltothenameintheoccurrenceofdiscountthatis
currentlyexamined(pathitem\name).Noticetheuseofreservedworditemthatmeansthe
current examined occurrence.
Thebareexpressiondiscount[where]\ratemightreturnmorethanoneoccurrence.To
computetheactualvalueoftheamount,youneedtopickuponlyone;thisisaccomplishedbythe
final[1].Thereisonlyonediscountthatmatchesthecondition;otherwise,onlythefirstmatching
recordispickedup.Asforsimplebracketoperators,ifnorecordmatches,anabsentvalueis
returned.
Suchclausescanbeaccumulatedtoreducethesubsetofoccurrencesasneeded.Ifyouchanged
yourdiscountconditionlisttohandlediscountperiods:
discount 1..n
name 1..1, class s
beginning 1..1, class d
ending 1..1, class d
rate 1..1, class r
Youcanselecttheappropriateratealongtheyearusinginvoicedate:
\invoice\line[1]\quantity
* \invoice\line[1]\price
* in2:\discount[where item\name = \invoice\customer\name]
[where item\beginning <= \invoice\date]
[where item\ending >= \invoice\date]\rate[1]
Thesubsetofdiscountoccurrencesisfirstreducedtothoserelatedtocustomername.Then,the
resultingsubsetislimitedtoratesthatbeginbeforeinvoicedate.Finally,occurrencesthatend
beforetheinvoiceareexcludedtoobtainthecorrectsubset.
Theorderoftheclausesiscrucial:restrictionsoftheoccurrencessubsetareappliedonebyone
fromlefttoright.Eachnodeofapathcanbefilteredusingwhereclauses,apathcancontainmore
thanoneclauseonmorethanonenode.Whereclausesandbracketoperatorscanbeusedtogether,
ifyouwanttoselectonlyoneoccurrence.
Whenusingambiguouspaths,bracketoperatorsandwhereclausesareappliedonthewholesetof
occurrencesofallthenodesaddressedbythepath.
Forexample,thepath\\mynode[23]thatreferstoaBusinessDocumentwiththreenodesnamed
mynodewith5occurrencesforthefirst,17forthesecondand24forthethird.Index23is
consideredglobal,the23 rd occurrenceofmynodeisthefirstoccurrenceofthelastnodenamed
mynode.
@@ Specifier
ThenodesofaBusinessDocumentmightormightnotbedefinedashavingvalues.Usually,nodes
thatgroupothernodesdonothavevalues,whileterminalnodeshaveavalue.
Inexpressions,thereisnooperatororinstructiontodeterminewhetheranodehasanassociated
valueornot.AmbiguouspathsinlargeBusinessDocumentscanbehardtomanage.
Ifyouhadahugedocumentwiththousandsofnodescalledmy_funny_node,somedefined
havingvalues,othersnot,youwouldneedtocheckallthosevaluesagainstaspecificcondition.
Youcannottestallofthemexplicitly:itwouldtakeagestoentertheValidationRules.
Therefore,yourequireauniquepaththataddressesonlymy_funny_nodesthataredefined
havingvalues.Todothisyouusethe@@specifier.
Forexample,thefollowingpathaddressesonlythoseofmy_funny_nodethataredefinedhaving
values,whateverthecardinalityisandwhethervaluesaresettosomethingotherthanabsent:
\\@@my_funny_node
StartwiththeMapthatgeneratesthedocumentforthepartnerrestaurant.Filltherecipientpartwith
copiesofsupplierfieldsfromtheinput.Thefollowingtableliststhemappingofdatafrominputto
outputnode:
\order\fax \order\supplier\address\fax
\order\caption\recipient\name \order\supplier\name
\order\caption\recipient\phone \order\supplier\address\phone
\order\caption\recipient\fax \order\supplier\address\fax
Inthistable,theusualpathsyntaxisused.Youcaneasilytranslateinformationtofillthe
appropriateexpressionfieldsintheMR_webToPartnerMap.
NowthatyouhavealmostfilledthenodesoftheBD_orderToPartnerBusinessDocument,switch
totheotheroutputofyourDMLBlock,theBD_billingDeliveryBusinessDocument.
WhatisinterestinginfillingBD_billingDeliveryisthecomputingofthechargefeesandamounts.
Computingthenodeamountrequiresyoutogothroughalltheoccurrencesofnodeline.Ifthe
valueisavailableinthevariableamount,thenyoucanexhibittheexpressionthatcomputesthe
valueofchargesthatis5%ofordertotalasfollows:
%amount * 0.05
Inaddition,youareabletocomputethepartner_feesvaluefromthevalueoftheamount
variableandtheratenodeofinputrates:
ThisexpressionselectstheratefrominputratesXMLdocumentusingthesuppliernamefoundin
theinputorderdocument.Then,thegrandtotalisquitesimple:
%amount * 1.05
Noticethatcomputingthefieldtotalisdoneonlyfromtheinput.InMaps,youcannotusethe
outputyouarecurrentlybuilding,eveniftotalisbasicallythesumofamountandcharges,you
cannotcomputeitthatway.
Thevaluesformappingtheremainingnodesof BD_billingDeliveryarecopieddirectlyfromthe
nodeswiththesamenamesinBD_orderFromWeb.Totelltheintegrationenginetoperformsuch
copies,youenterthepathstothesourcenodesaselementaryrulesintheMap.
Thisispossiblefornearlyeverynodeoftheoutput.Anupcomingchapterdescribeshowtohandle
thecaseofmultiplyoccurringnodes(nodeswithcardinality1..nor 0..n).
ThefollowinggraphicillustrateswhatyourMapshouldlooksimilartoatthispoint:
Suchprimitiveexpressionsmightworkfinewhendealingwithoutputsthatcloselyresembleinputs.
Ontheotherhandmanymappingsneedtoprocesscomplexandversatiledataandmodifytheir
behaviorbasedonthevariationsofdatatheyreceive,inwhichcaseprimitiveexpressionsareless
useful.
Insuchsituations,eachtimeyousupplytheintegrationenginewithdifferentdata,thesetof
expressionsyouenteredmightresultinadifferentoutput.Todeterminehowtogiveyour
expressionsthecapabilitytomakedecisionsandthereforebehavedifferently,youmustuse
conditionalstatements.
Theintegrationengine,andcomputersingeneral,workinasimilarway.Whilepeoplecanask
questions,theintegrationenginecancheckBooleanexpressions.ABooleanexpressionisbasically
anythingthatrepresentsoneoftwovalues,suchastrue/falseor zero/non zero.Theclassof
suchexpressionsisclassB.
%revision = 19
\customer[%customer_index]\name = "John Doe"
\invoice\date <> \invoice\delivery_date
%tax_rate * 1.05 = %general_tax_base
Testingforequalityisdonewithanequalsign,whiletestingfordifferenceisdoneusingtwoangle
bracketsformingabox.Whenyouusetheseoperators,theintegrationengineevaluatesand
comparesbothsides.Whenusing=,ifthevaluesarethesame,theresultistruewhileitisfalse,if
thevaluesaredifferent.Operator<>evaluatesstrictlytheopposite:trueifdifferent,falseifthe
same.
Testingfordifferenceorsamenessoperatesonanytypeofvalues:youcancomparenumbers
(classesB,IandR),dates(classD),strings(classS)orraw-data(classV).Symbolicvaluesabsent
andnullarehandled:anyvalueisalwaysdifferentfromabsentornull,butabsentisthesameas
absent,andnullisthesameasnull.
Donotforgetthatimplicitconversionsarealwaysactive,youcantest"69"(thestring)and69(the
wholenumber)forsameness.Whentheintegrationenginecomputessuchcomparison,itfirst
promotesthewholenumberintoastring,thentestsforsamenessordifference.Thiscanleadto
unexpectedbehaviors:whentesting"3.14"against3.14,promoting3.14resultsinthestring
".314e+1"thatisreallydifferentfrom"3.14".
Sometimesyouneedtodeterminewhethersomethingiswithinasetofvaluesornot.Twooperators
existthatacceptlistsofvaluesasrightoperand:inandoutasshowninfollowingexamples:
Theoperatorinevaluateswhethertheleftoperandisthesameasoneofthevaluesintherightlist
whileoutdoesexactlytheopposite.Whenyouusesuchexpressions,theintegrationengine
comparestheleftsidewithcomponentsintherightside,oneafterone,untiltheresultsisknown:if
%revisionvalueis"1.1",literals"1.6"and"2.0"willnotbeevaluated.
Determiningwhethertwovaluesarethesameornot,issometimesnotenough.Youmightwantto
knowwhethersomequantityisgreaterthanthatofanother,orwhetheravalueislessthansome
othervalue.Performingsuchtestisinvokedwiththe>and<operators,respectively.Thequestion
theyansweriswhetherthevalueontheirleftsideisgreater(>)orlessthan(<)thevalueontheir
rightside.
Samenessandordercanbecombinedingreaterthanorequalstoandlessthanandequalsto
operators:>=and<=.
Testingorderisquitenaturalonnumbersordates.ForordertestinginBooleanexpressions,true
takesorderprecedenceoverfalse.
Furthermore,youcancomparestringswhichresultsmightappearsurprising.Computersare
basicallyunabletomanipulateanythingotherthanwholenumbers.Whenyouinvoke<or>
operatorswithstrings,theintegrationengineisforcedtousetheseriesofwholenumbersthat
codesthestrings.
Theintegrationenginesubtractstheseriesoftherightsidestringfromtheoneoftheleftsidestring.
Ifthevalueobtainedisnegative,thenleftsideisconsideredbeinglessthanrightside.Thisis
becauseofthealgebraicequivalence:a < b <=> a b< 0.
Ifthestringsareboth,encodedusingASCIIderivedcharactersets(ISO8859 andUnicode
variations),thispreserveslexicographicalorderforromanletters.Stringcomparisonisbasedonthe
orderthatisusedincommondictionaries.
Comparingraw-datavalues(classV)isnotsupported.
Symbolicvaluesabsentandnullarenotconcernedwithorder:testingorderwithabsentornull
resultsinundefinedbehavior.
YoucanchooseamongfourBooleanoperatorsinDMLexpressions:and,or,xorandnot.
TheandoperatorcombinestwoBooleanexpressions.Itcanrepresentatruevalueonlyifbothleft
andrightexpressionsthatitconnectsalsoaretrue.Toshowhowtheandoperatorworks,people
thatworkwithcomputerssimilartodrawsomethingtheycallatruthtable,whichtellsyouwhatthe
resultoftheconnectedexpressionsis.Thefollowingisthetruthtablefortheandoperator:
True False
True True
TheoroperatorlinkstwoBooleanexpressionsbutproducesatruevalueifeitherBoolean
expressiononleftorrightrepresentsatruevalue.Thisoperatorcanproduceafalsevalueonlyif
bothofitsoperandsarealsofalse.
Thefollowingisthetruthtablefortheoroperator:
True True
True True
Theandandoroperatorshaveacloserelationshiptocommonsense.Askingyourselfwith
questionssimilartoDo I store the meat Ive just bought in the fridge or the freezer?
thatinvolvethewordsandororarequitethesameasusingtheoperatorsinexpressions.
ThexoroperatorconnectstwoBooleanexpressionsandreturnstrueifoneandonlyoneofthe
expressionsitconnectsistrue.Itisjustsimilartotheoroperatorexceptthathavingtwotrue
meansfalse:
True True
True False
ThelastBooleanoperatoroperatesonlyononeBooleanexpression.Withthenotoperatoryoucan
reversethevalueofaBooleanexpression.Thismeansthattheresultingvalueisfalseiftheoriginal
wastrue,andtrueiftheoriginalwasfalse.
WithBooleanoperatorsyoucanconnectsingleteststobuildbiggerexpressionsthatturntrueor
falseincomplexsituations.Justsimilarto+,-,*and/operatorsinamathformula,and,or,xor
andnotcanbeusedasmanyasneededtomatchthecorrectsituation.Thefollowingisthe
completeexpressionthatdetectswhetherayearisaleapyear:
Thisexpressionevaluatestotrueonlywhentheyearisamultipleoffourwithoutbeingacentury,
exceptforcenturiesthataremultiplesoffourhundredtheremainderfunctionisusedto
determinewhetherayearisamultipleof4,100or400.
Whenperformingthisexpression,theintegrationenginefirstevaluatestheexpressiontowhichthe
notoperatorisapplied,thenitconnectstheresultswiththeandoperator,and,finallycomputes
theoroftheresultwiththelastpartoftheexpression.Similartobasicmathoperators,theorderof
evaluatingBooleanoperatorsisstrictlyruledbypriorityorder:
Theifthenstatementlooksasfollows:
Whenprocessingthisexpression,theintegrationengineevaluatestheBooleanexpressionbetween
ifandthenreservedwords.Iftheevaluationreturnstruethelistofstatementsenclosedbetween
thecurlybrackets{and}isevaluated,otherwiseitisignored.Thisistotestwhetherthedateofthe
invoiceiswithinyear2006.Ifso,oneisaddedtothecontentsofthevariableinvoices2006;asa
result,thenumberofinvoicesof2006isdetermined.
Whiletheifthenstatementisawaytoactivatesomepartofanexpressiononlywhenacertain
conditionistrue,theif then elsestatementtellstheintegrationenginetoevaluateoneset
ofinstructionswhentheconditionistrueandanothersetofinstructionswhentheconditionis
false.Hereisanexampleofthisstatement:
if \bottle\capacity = 75 then
{
"bottle"
}
if \bottle\capacity = 150 then
{
"magnum"
}
if \bottle\capacity = 300 then
{
"jeroboam"
}
if \bottle\capacity = 600 then
{
"maalem"
}
if \bottle\capacity = 900 then
{
"salmanazar"
}
if \bottle\capacity = 1200 then
}{
}"balthazar"
}}
if \bottle\capacity = 1500 then
}{
}"nabuchodonosor"
}}
Asanalternativetomultipleandunreadableifthenelsestatements,youcanuseaswitch
statement.Thisstatementactivatesdifferentsetsofstatementsdependingonthevalueofacertain
expression.Ifyourewritetheprecedingexamplewithaswitchstatement,theexpressionwouldbe
thefollowing:
switch \bottle\capacity
{
case 75:
{ "bouteille" }
case 150:
{ "magnum" }
case 300:
{ "jeroboam" }
case 600:
{ "maalem" }
case 900:
{ "salmanazar" }
case 1200:
{ "balthazar" }
case 1500:
{ "nabuchodonosor" }
}
ThisexpressionreturnsthecorrectnameoftheChampagnebottlesizeprovidedtheinputcapacity
fallswithinthelist75,150,300,600,900,1200,1500.Ofcourseif\bottle\capacityissetto
noneofthesevalues,theswitchstatementdoesnotevaluateanyofthesetsofstatementswithin
itsstructure.
Tomakesurethattheintegrationengineevaluatesatleastonesetofstatementsinaswitch
statement,youcanaddadefaultcaseattheveryend:
switch \bottle\capacity
{
case 75:
{ "bouteille" }
. . .
case 1500:
{ "nabuchodonosor" }
default:
{ "unknown size" }
}
Theintegrationengineevaluatesthesetofstatementsthatisboundtothisdefaultcasewhennone
oftheothercasesmatchesthevalueoftheswitchexpression.
Youoftenusetheswitchstatementtocheckwhetheranexpressionexactlymatchesaspecificvalue
suchasthenumber1500orthestring"yes".But,sometimesyoumightwanttoevaluateasetof
statementsiftheexpressionsfallwithinasetofindividualvaluessimilarto3,19or27orarangeof
values,suchasanynumberbetween1and16.Insuchsituations,youcanlistallthepossible
valuesonasinglecase,orconnecttheboundsofarangewiththereservedwordtoo.
switch \bottle\capacity
{
case 75, 150:
{ "available, usually" }
case 300 to 600, 1200:
{ "only upon order" }
case 900, 1500:
{ "too expansive" }
default:
{ "not known at all" }
}
Makesurethatthevalueyouareevaluatingcannotsatisfymorethanasinglecase,ashappensinthe
followingexample:
switch \bottle\capacity
{
case 75, 150, 400:
{ "available, usually" }
case 300 to 600, 1200:
{ "only upon order" }
case 900, 1500:
{ "too expansive" }
default:
{ "not known at all" }
}
Thenumber400isboundtoeitherthefirstorsecondsetofstatements(400isintherange300to
600).Ifthetestedcapacityis400,theexpressionisalwaysreturnsthevalue"available,
usually".Thisisbecausethecase 75, 150, 400istestedfirst,preventingthesetofstatements
boundto300 to 600, 1200fromgettingachancetobeevaluatedatall.
Testingusingswitchcaninvolveanytypeofvaluethathasliterals(meaningallclassesexceptV).
Promotionsareappliedwheneverrequiredandrangesofvaluesarelegalevenonbooleans,dates
andstrings:alloftheseareordered(false<true).
However,symbolicvalues(nullandabsent)cannotbeusedascasesvalues.
Thisworksfineinmostcases,butinsomecomplexsituations,addressingtheIDnodewithan
ambiguouspathisnotaccurateenough.Imagineyourinputdocumentcontainsboth,customerIDs
andsupplierIDs,andthatyouneedonlytocheckcustomers.
WhatyouneedisawaytodiscriminatecustomerIDsfromsupplierIDs.Mostofthetimethe
structureoftheinputisdiscriminative:
members
customer
id
name
address
.
.
.
phone
fax
discount_rate
supplier
id
name
address
.
.
.
phone
fax
Thesecustomerrecordsincludeadiscount_ratethatisnotpresentinsupplierrecords.Youcan
usethedefinedoperatortocheckwhethertheidisoneofyoursupplierorcustomer:
ThewhereclausematchesonlyforIDnodesthatdohaveasiblingnodenameddiscount_rate.
Whenprocessingadefinedoperatorstatement,theintegrationenginecheckswhetherthepaththat
followstheoperatorleadstospecifiednode.Ifso,thestatementisevaluatedtotrue,otherwise,the
valueisfalse.
Inthepreviousexample,statementsenclosedbetweenthecurlybracketsareevaluatedonlyfor
customerIDsthatarenot19characterslong.
Youcanreversetheconditionusingtheundefinedoperatorinthesameconditions.
Thisexpressionchargesthecustomerwithavariableratewheneverthepaymenthasbeenmade
usingaVISAcard.Thefollowingtabledescribesthedecisionconditions:
notVISA none
VISA, 13%oftheordertotal
orderamountincludingcharges
islessthan75
VISA, 1.5%oftheordertotal
orderamountincludingcharges
ismorethan75
Inthatexpression,thetotalamountoftheorderisused:thecontentsofvariable%amount isread
andtestedagainstthedifferentthresholdstoselecttheapplicablerate.Howtosetthevalueof
%amountisdescribedinanupcomingchapterofthisbook.
TomakeVISAextra-chargesoperational,replacetheexpressionboundtothenodetotalintheMR_
webToBillingMap.
Inthisgraphic,theroundfunctionisusedthattheresultofthecalculationswillfitintothedefined
fieldparametersoftotal.
Naturally,executingthistypeofrepetitivetaskcanbeboringandpronetoerrors.Ideally,in
programmingyouprefertowriteexpressionsasconciselyaspossible,notonlybecauseshort
expressionsareeasiertodebug,understandandmodify,butalsobecausetheyrequirelesstyping.
Onewaythatcomputerlanguagessolvethisproblemisbyusingprogrammingstructuresknownas
loops.Basically,aloopisasortofstatementthatmakestheintegrationenginerepeatacertainset
ofstatements,thereforerequiringyoutoenterthemonlyonetimeinthecode.
LoopsinDMLexpressionsarebuiltaroundtheloopreservedword,followedbythenumberoftimes
youwanttorepeatandthesetofstatements.Thefollowingisanexampleofabasicloop:
1 %address := "";
2 %index := 1;
3 loop (count(\\address\lines))
4 {
5 %address := %address + \\address\lines[%index] + "\n";
6 %index := %index + 1
7 };
8 %address := %address + \\address\zip + " "
9 + \\address\city;
10 %address
Thenumbersatthebeginningofeachlinearenotpartofthecode.Theyareaddedtofacilitate
explanations.
Theloop () { }statementextendsfromline3toline7.Similarlyasinconditionalstatements,
curlybracketsareusedtoenclosetherepeatedsetofinstructions.
Thenumberoftimesyouwanttorepeatisenteredbetweenparentheses.Thiscanbeanylegal
expressionwhichvalueiscompatiblewiththewholenumbers(classI).Useacalltothefunction
countthatreturnsthenumberofoccurrencesofaspecifiednode.Thisinstructstheintegration
enginetoevaluatelines5and6foreachexistinglinenodesintheinputBusinessDocument.
Theremaininglinesofthisexpressionmanipulatethevariablesindexandaddress.Thepurposeof
thisexpressionistogenerateasinglestringthatcontainsthecompleteaddress,includingthelines,
zipcode,andcityname.
Forabetterunderstanding,imaginewhattheinputis(withdata)andtracetheexpressionthatis
detailing,whatisdonestepbystep:
Input data
node address
node lines, occurrence 1, value Sherlock Holmes
node lines, occurrence 2, value 221b Baker Street
node zip, value NW1 6XE
node city, value London
Trace of evaluation
Line Evaluation
1 Valueofvariableaddresssettoemptystring""
2 Valueofvariableindexsetto1
3 Evaluationofcount(\\address\lines),resultis2
4 Enteringtheloop
6 Variableindexisincremented,newvalueis2
7 Checkingwhethertheloopends;atthistimetheloophasbeenperformedonly
onetimeoutoftwo,sogobacktoline4
4 Continuetheloop
6 Variableindexisincremented,newvalueis3
7 Checkingwhethertheloopends;atthistimetheloophasbeenperformedtwo
outoftwo,sogoendtheloop,gotoline8
8-9 Appendzipcodeandcitynametoaddressvariable,itsvalueisnow:
"Sherlock Holmes221b Baker StreetNW1 6XE London"
10 Returnthevalueofaddressasexpressionresult
Forthisexample,youcouldhaveusedexplicitconcatenationsoflinesintheaddress,asfor
example:
\\address\lines[1] + "\n"
+ \\address\lines[2] + "\n"
+ \\address\zip + " " + \\address\city
Thisworksfinewithtwooccurrencesofnodelines,butyouwillhavetochangetheexpression
wheneveranewoccurrenceappears.Withoutusingtheloopstatement,itwouldbeimpossibleto
collectallthelinesincaseswhentheirnumbervariesfromtimetotime.
Amoreconciseandefficientwaytoperformthispreciseexampleisdescribedinanupcoming
section.
Reaching a condition
Repeatingusingloopstatementisuseful,butyouneedtoknowtheexactnumberofrepeatsbefore
enteringtheloop.Thiscanprovelimitingandinconvenient.Itisalsopossibletorepeatstatements
untilaspecificconditionismet.Todothis,youusethewhileinstruction.
Thewhileinstructionrepeatsthesamesetofstatementsjustasloopinstructiondoes,butit
performsthattaskaslongasacertainconditionisverified.Youcanrewritethepreviousexample
usingawhileloop,asfollows:
1 %address := "";
2 %index := 0;
3 while (%index < count(\\address\lines))
4 {
5 %index := %index + 1;
6 %address := %address + \\address\lines[%index] + "\n"
7 };
8 %address := %address + \\address\zip + " "
9 + \\address\city;
10 %address
Thesetofstatementsenclosedincurlybrackets{ }isrepeatedaslongasthevalueoftheindex
variableisnotmorethanthenumberofoccurrencesofnodelines.
Imagineacasewhereyouarelimitedbythelengthoftheresultsyoucanhandle:youwanttostop
beforethelastline,whenyourlimitisreached.
Justaddaconditiontothewhile:
1 %address := "";
2 %index := 0;
3 while (%index < count(\\address\lines) and length
(%address) < 50)
4 {
5 %index := %index + 1;
6 %address := %address + \\address\lines[%index] + "\n"
7 };
8 %address := %address + \\address\zip + " "
9 + \\address\city;
10 %address
Thewhileloopisstoppedwheneverthelengthofaddressreaches50characters.
AconditionthatstopsawhileloopisaBooleanexpressionthatcanbeascomplexasneeded.
Rememberthatthisconditionischeckedateachrepetitionoftheloop,beforeanyofthestatements
includedintheloopareevaluated.Itispossiblethatthesetofinstructionsincurlybracketsmight
neverbeenevaluatedatall.
Usingwhileismoreflexiblethanusingloop,butcanpresentrisks.Oneofthemostcommon
problemswithsuchloopsisknownasendlessloops,whichmeansthattheintegrationengine
evaluatesthesetofstatementsincludedintheloopbutneverstops.Iftheintegrationengineis
caughtinanendlessloop,itmightseizeandexhaustallthehostresources,forcingyouto
reinitializetheserver.
Themaincauseofendlessloopsisaninappropriatestopcondition.Whenyouusewhile,make
surethattheconditionwillatsomepointbecomefalse.
Youcandothisusingeitherthebreakornextinstruction.breakexitsthecurrentinnerloopwhile
nextgoesdirectlytothenextrepeat.Itcanbeusedinyouraddressexampletoskipemptylines:
%address := "";
%index := 0;
while (%index < count(\\address\lines) and length(%address) < 50)
{
%index := %index + 1;
if (length(\\address\lines[%index]) = 0) then next;
%address := %address + \\address\lines[%index] + "\n"
};
%address := %address + \\address\zip + " "
+ \\address\city;
%address
Intheprecedingexamplewiththeboldlineadded,thecontentsofanemptyoccurrenceofthe
nodelinesisneverappendedtothecontentsofaddress.Wheneveranemptylineisencountered,
theconditionintheboldlineisverifiedandtheintegrationengineexecutesthenextinstruction.
Thestatementthatupdatesthevariableaddressisignored.
Thenextinstructionisusuallyusedtoavoidcomplexexpressionsinvolvingnumerousnested
conditionalsthatneutralizelargepartsofthesetofstatementsthatarerepeated.Usingnext
instructionsmakescodemorereadablebyeliminatinglongseriesofifclauses.
Considerthefollowingexpressions:
while () while ()
{ {
if condition1 then if not condition1 then next;
{
if not condition2 then next;
if condition2 then
{ }
if condition3 then
{
}
}
}
Theleftandrightexpressionsareequivalent.Whatmakestherightonemoreelegantandconciseis
theuseofthenextinstruction.Whilereading,afteryouhavepassedthelinethatdealswith
condition1,thistestisnolongerinyourmind.
Theusefulnessofthebreakinstructionislessobvious.Tounderstandhowbreakisessential,
reworkyourexampleaboutaddresses.Usethefollowingexpressioninwhichthelengthoftheresult
islimitedto50characters:
1 %address := "";
2 %index := 0;
3 while (%index < count(\\address\lines) and length(%address) < 50)
4 {
5 %index := %index + 1;
6 %address := %address + \\address\lines[%index] + "\n"
7 };
8 %address := %address + \\address\zip + " "
9 + \\address\city;
10 %address
LimitingthefinallengthisaccomplishedbythesecondpartoftheBooleanexpressionatline3.This
isnotcorrect.Thelengthisverifiedtooearly.Thecontentsofaddresscanbelessthanfifty
characterswhenthetestofline3isperformed.Butifthelineyouappendatline6istoolong,the
stringwilloverflow.
Thesolutionistodeferthetestasinthefollowingexpression:
1 %address := "";
2 %index := 0;
3 while (%index < count(\\address\lines))
4 {
5 %index := %index + 1;
6 if length(%address)+length(\\address\lines[%index])+1 > 50 then
7 {
8 break
9 };
10 %address := %address + \\address\lines[%index] + "\n"
11 };
12 %address := %address + \\address\zip + " "
13 + \\address\city;
14 %address
Inthisexpression,thelengthischeckedatthetimethepartabouttobeconcatenatedisavailable.
Theloopisstoppedatthatmomentifthereisnotenoughroomleftintheresultingstring.Loops
cancontainotherloopsinthesetofstatementstheyrepeat.Youcanaddasmanynestedloopsas
yourequire.Butrememberthatbreakandnextoperateonlyontheinnerloop,thatis,theone
closesttothem.
Thisexpressionworks,butignoresorderlinesafterthe2 nd .Thisisnotacceptable:youneedtotake
intoaccountalloccurrencesofthelinenodetobuildthecompletetext.Aloopisneeded.The
expressionthataccumulatesalltheorderlinesintothetextis:
Thisworksfinefororderswithlessthanonehundredlines,butbecomeslessandlessefficientasthe
numberoflinesgrows.Whatistimeconsuminginsuchastructureisthattheintegrationengine
doesnottodetectthatyouactuallywanttopickupoccurrencesoflineoneafteranother.Inthis
situation,eachaccesstolinerestartsfromtheveryfirstoccurrence.Thetimeneededtoperform
thisloop on n occurrencesisroughlyproportionalton.
Abettersolutionisshowninthenextchapter.
Inthefollowingpages,youwillgoonestepfurther.Thefollowingquestionsareanswered:
l HowdoImapthroughasetofoccurrences?
l HowdoIgenerateasmanyoccurrencesasrequiredbytheoutputBusinessDocument
definition,orasmanyasdoexistintheinput?
l HowdoIcopyacompletetreeofinputnodesverbatimtotheoutput?
Whilethismethodworksfine,itisverycostlyintermsofsystemresources.Thisisbecausethe
bracketoperatorishandledindividuallybytheintegrationengine.Asaresult,whentheintegration
enginecomestopickupthenth occurrenceofanode,itdoesnotrememberthatitjustreadthe
preceding(n-1) th occurrence.Therefore,itrestartsthesearchfromthefirst.Whenprocessinglarge
numbersofoccurrences,thisrequirestoagreatnumberofoperations.
Theloop onstatementinstructstheintegrationenginetogothroughallexistingoccurrencesofa
specifiednodeandperformsometaskforeachone.Youcantranslatethepreviousexampleusing
themoreefficientloop on:
1 %address := "";
2 loop on \\address\lines
3 {
4 %address := %address + this + "\n";
5 };
6 %address := %address + \\address\zip + " "
7 + \\address\city;
8 %address
Inthisexample,line2tellstheintegrationenginetogothroughalloccurrencesof
\\address\linesnode,onebyone.Foreachoccurrence,thesetofstatementscontainedbetween
thecurlybrackets{ }isevaluated.
Inthissetofstatements,youcanusethereservedwordthistorefertothecurrentoccurrence.this
isinvokedinline4toappendthecontentsofthecurrentlinetotheaddressvariable.Thethis
keywordalwaysstartsapathtoanodeandcannotbefilteredusingeitherthebracketsoperatoror
where.However,pathsstartingwiththiscanaddressanynodeintheBusinessDocument:youcan
usetheparentoperator..,andsingleanddoublebackslashconnectorstomoveallaroundthenode
tree.
Aswithloopsusingloopandwhileinstructions,youcaninvokethenextandbreakinstructions
insidealoop onstatement.Theyoperatebyeitherjumpingdirectlytothenextoccurrenceor
interruptingtheloop.Toignoreblanklines,youchangethepreviousexpressionto:
1 %address := "";
2 loop on \\address\lines
3 {
4 if (length(this) < 1) then next;
5 %address := %address + this + "\n";
6 };
7 %address := %address + \\address\zip + " "
8 + \\address\city;
9 %address
Anotherwaytohandleblanklinesistofilterthelinesdirectlyintheloop oninstructionargument.
Thisworksbecausetheloop oninstructionhasthecapacitytogothroughanysetofoccurrences
ofnodesaddressedbyanylegalpath.Thismeansyoucanusepathsthatincludewhereclausesor
bracketoperators,orthataddressfromnonetoanyoccurrences.Thepreviousexamplecouldlook
similartothis:
1 %address := "";
2 loop on \\address\lines[where length(item) <> 0]
3 {
4 %address := %address + this + "\n";
5 };
6 %address := %address + \\address\zip + " "
7 + \\address\city;
8 %address
Thesetofstatementsboundtotheloop oninstructionisrepeatedonlyforeachlinesnodethatis
notblank(lengthisnotzero).
Youcanalsouseambiguouspaths.Alltheoccurrencesofalltheaddressednodeswillbecovered.
InEdifact/Invoicedocuments,segmentsappearinseveralsegmentgroups(references,
documentaryrequirements,currencies).Asaresult,severalnodeswiththenameDTMappearin
theprebuiltEdifactBusinessDocumentsprovidedintheintegrationengine.Ifyouwanttoperform
anoperationonallthesesegments,youcanuseloop on:
loop on \\DTM
{
}
ThisstatementfirstevaluatestheenclosedsetofstatementsfortheDTMsegmentsintheheaderof
theEdifactdocument,thenfortheDTMsegmentsofsegmentgroup1,thenforthoseofsegment
group3untiltheverylastDTMsegmentofthedocument(segmentgroup51)hasbeencovered.
Inthesetofstatementsboundtothisloop oninstruction,youcanusethisasareferencetothe
currentDTM.SinceallDTMsegmentshavethesamestructure,apathsimilarto
this\C507\D2005alwaysaddressessomething,whateversegmentgrouptheDTMsegmentis
includedin.However,apathsimilartothis\..\QTYcannotbeusedbecauseonlysegmentgroups
1,33and49havebothDTMandQTYsegments.
Whenloopingwithambiguouspaths,theonlyrequirementistoaddressnodesthatexist.Evenif
eachDTMsegmenthasdifferentstructures,loopingwouldbepossible,althoughonlypathsto
nodesthatarecommontoalltheDTMswouldbelegal.
Theloop onstatementcangothroughanysetofoccurrences.Youcannotonlyuseapathtoa
singlenodeortoseveralnodes(ambiguouspaths),butalsospecifymoremultiplepaths.Imagine
youwanttogothroughallCTAandCOMsegmentswithinaBusinessDocument.Todothisyou
enterthefollowing:
ThiscodegoesthroughalloccurrencesofallCTAsegmentsandthenalloccurrencesofCOM
segments.Intherepeatedsetofstatements,thisrefersfirsttoCTAnodesandthentoCOMnodes.
Similartostandardloopsandwhileloops,loop onstatementscanincludeanotherloopinsidethe
setofstatementstheyrepeat.Insuchasituation,thekeywordthisalwaysreferstotheinnerloop.
Inthepreviouschaptersofthisguide,yousawstructuresthatoperateonconstants,variablesor
inputdataandhowtodealwithmultipleoccurrencesofdataininputnodes.
NowyouhavetoconceiveaDMLBlockwhosetaskistoperformthefollowingmapping:
Thetaskhereistoclonethesingleincomingsetofdatatofilltwomandatoryoccurrencesof
segments;datafieldsa,bandcarecopiedverbatim.TheoutputBusinessDocumentisdefinedas
follows:
s1..n
a1..1, class s
b1..1, class s
c1..1, class s
Instructingtheintegrationenginetocopyinputnodesa,bandctotheoutputnodeswiththesame
namesiseasy:justdefineaMapwiththeexpressions:
Output Bound
node expression
a \a
b \b
c \c
ThisMaplackssomethingessential:awaytospecifythatyouwanttogeneratetwooccurrencesof
segments.
Toinstructtheintegrationenginetodothis,youinvokethetimesinstructionintheexpression
boundtonodes:
Node Bound
expression
s 2 times
a \a
b \b
c \c
Thetimesstatementiscomposedofthereservedwordtimesprecededbyawholenumber(classI)
valueexpression.Whenprocessingthisstatement,theintegrationenginecomputesthefrontal
expressionvalueandthengeneratesthatnumberofoccurrences.
Thetimesstatementdoesnotgenerateavalue.Itsfunctionistocalculateanumberof
occurrences.Suchastatementisknownasacardinalitystatement.Itcanonlybebound,inMaps,
toanodewithcardinality0..1,0..nor1..n.
Cardinalitystatementsarerequiredwhentheintegrationenginecannotdetermineitselfhowmany
occurrencesofanodemustbecreated.Thisisquiteobviousformultiplenodes(0..nand1..n).
Foroptionalnodes(0..1)itismoresubtle.Fornodesdefinedhavingvalue,asfarasanexpression
isboundtothenode,itisgenerated.Fornodesdefinednothavingvalue,youmustbindan
expressionwithatimestatementifyouwantanoccurrenceofthatnodetobegenerated.
Whendealingwithanodethatisbothmultipleanddefinedashavingvalue,youneedtotellthe
integrationenginenotonlytogenerateacertainnumberofoccurrences,butalsotosetthevalueof
eachoccurrence.Thisisaccomplishedusingthetimesdoinstruction.Enhanceyourexample
withthenewoutputBusinessDocumentdefinedasfollows:
s1..n, class i
a attribute, 1..1, class s
b attribute, 1..1, class s
c attribute, 1..1, class s
Whatchangeshere,isthatthesegmentholdsanumber(thefirstoccurrenceis1andthesecondis
2)anda,bandcarenowattributes.Youmustusetimesdoinconjunctionwithavariablein
ordertonumberthesegments:
s 2timesdo{%index:=%index+1;%index}
a \@a
b \@b
c \@c
Theintegrationenginecontinuestogeneratetwooccurrencesofthesnode,buteachtimeanews
iscreated,theblockenclosedincurlybracketsisevaluated.Whenthevariableindexhasaninitial
valueof0,theblockevaluatesto1forthefirstoccurrenceofsand2forthesecond.
Thefollowinggraphicshowshowoutputdataisgeneratedusinginput:
Datafieldsareclonedandthesegmentnumbered.
Whenusedonanodethatgroupsothernodes,youtelltheintegrationenginetogeneratethe
groupseveraltimes.Asmanyoccurrencesasneededofallgroupmembersaregenerated.
Totelltheintegrationenginetogeneratewhilecoveringasetofoccurrences,youusethefor each
statement.Thisstatementbehavesexactlysimilartothetimesstatement,exceptyouspecifyalist
ofpathsthataddressthenodesintheinputstogothrough,insteadofjustanumber.While
coveringoccurrences,thepathtothecurrentnodeisreferredtoviathis,justsimilartoinloopon
loops.
Thecommonuseofafor eachstatementistocopyagroupthatoccursmorethanonetime,just
havingagroupmemberchanged.ConsiderthefollowingBusinessDocument:
invoice 1..1
line 1..n
item_id 1..1, class s
quantity 1..1, class i
unit_price 1..1, class r
amount 1..1, class r
Whenfedasinputtotheintegrationengine,theamountofeachlineisfilledwithabsent.Whatyou
wanttoaccomplishwithaDMLBlockistofillthisfieldwiththeappropriatevalue.
Forthattask,inputandoutputBusinessDocumentsarethesame.YoucreateaMapthatcopiesall
theinputtotheoutput,exceptfortheamountthatshouldbecorrectlyfilled.Thefollowingisan
exampleoftheMap:
invoice
item_id this\item_id
quantity this\quantity
unit_price this\unit_price
Whileprocessingtheexpressionboundtotheoutputnodeline,theintegrationenginecountsthe
numberofoccurrencesoflineintheinputandcreatesthatnumberofoccurrencesoflineinthe
output.
Eachtimeanoccurrenceoflineintheoutputiscreated,theintegrationenginecreateseach
memberoftheoutputgrouplineusingthecorrespondingboundexpression.Asaresult,the
membersitem_id,quantityandunit_pricearecopiedfromtheinput.Noticetheuseofthisto
refertothecurrentinputnodeline.Theoutputvalueamountiscomputedusingvaluesunit_
priceandquantityretrievedfromtheinput.
Thefollowinggraphicillustratesthetasks,withexampledatavaluesillustrated:
Youcanusetwovariationsofthethiskeywordtoobtainmoreinformationabouttheprogressof
thecurrentloop(eitherinalooporinafor eachstatement).
Todeterminewhetherthecurrentoccurrenceisthefirstinthecollection,youcanusethisisfirst
thatevaluatestoabooleanwhichistruewhenthisreferstothefirstoccurrenceofthesetcurrently
covered.
Thevariationthisindexevaluatestoanintegerwhichistheindexoftheoccurrencethiscurrently
refersto.Thatindexrangesfrom1totheactualnumberofoccurrencesinthecoveredset.When
thethiskeywordisconnectedtoaloop ora for each statementwithmultipleorambiguouspaths
todocumentfields,theindexisconsolidatedamongalltheoccurrencesaddressedbythestatement
arguments.
Novariationsimilartothisislastdoexiststodeterminewhetherthisisthelastelementofa
browsedcollection.ThisisbecausesuchadeterminationistrickyandusuallyweakensDMLBlocks
executionperformances.However,youcantestthecurrentindexagainstthenumberofaddressed
occurrencestodeterminewhetheryouvereachedtheendornot,similartoin:
if (thisindex = count())
{
}
Insuchsituation,neverforgettouseanintermediatevariabletostorethecountofoccurrences.
Performingcountstakesusuallyalongtime,sotakecareofdoingsuchataskaslessaspossible.
Tokeepexecutiontimeacceptable,ratherthanusinganexpressionsimilartothefollowing,which
countsonlyonetimeratherthancountingeachtimeanoccurrenceisprocessed:
loop on \\CTA
{
if (thisindex = count(\\CTA))
}
usethisone:
%tempo = count(\\CTA);
loop on \\CTA
{
if (thisindex = %tempo)
}
Allthevariationsofthisareread-onlyobjects.Thismeansyoucannotusethisindexinconjunction
withtheassignmentoperator(:=)togodirectlytoonespecificoccurrenceofthecoveredset.
Expressionssimilartothefollowingdonotmovetothefourthoccurrenceofaset;theyareillegal:
thisindex := 4
Tobemoreefficient,youcanusethetreestatementtoperformblindcopiesofasub-treeofnodes
fromtheinputtotheoutput.Atreestatementiscomposedofthereservedwordtreefollowedbya
pathtoanode.Thenodethatyoureferenceinthestatementcangrouptogetherotherdependent
nodesandgroups.Atreestatementisalwaysthesinglestatementofanexpression.Thisis
commonlyreferredtoastreeexpressionsratherthantreestatements.
Whenyoubindatreeexpressiontoanoutputnode,youtelltheintegrationenginetocreatethe
outputnodefromadirectandcompletecopyoftheinput.Iftheoutputnodegroupsothernodes,
allexpressionsboundtothosenodesareignored.
Youcannotusetreeexpressionstocopyanythingintoanything:sourceandtargetshouldsharea
commonstructure.Namesarenotimportant,onlystructure.Whateverthenames,youcanusethe
treeinstructionif:
l Thesource(inputpartthatiscopied)andthetarget(outputpartthatisgenerated)are
structuredsimilarly:samenumberofnodes,withgroupsbeingatthesameplace.
l Cardinalitiesarecompatible:youcancopyanodethatis0..1intoanodethatis0..nwhilethe
oppositeisnotpossible.
l Classesarecompatible:whentheclassofthetargetisdifferentfromthesource,implicit
conversionmustbeusabletogeneratetooutputfromtheinput.
Ifalltheseconditionsareverified,theintegrationenginegeneratesthepartoftheoutputfrom
valuesintheinput.Nodesarecopiedoneafteranother.Groupsandoccurrencesarecreatedsothat
thefinaloutputisthesameastheinput.
Unsimilartousualotherelements,choiceparentsarenotrealnodesofBusinessDocument
instances.Theyarejustadefinitionofwhatispossiblewithinthedocumentinstances.Asa
consequence,namesofchoiceparentsneverappearinpathtonodes(seechapterGettingdata
frominput:Pathstonodesonpage59).
Basically,choiceparentsdefinealternativesinthecontentsofapartofaBusinessDocument.
Imagineyoucreateanintegrationthatgeneratesdeliverynotes.Deliverynotesusuallyinclude
contactinformationthatcanbeusedtocallthecustomer,forexample,toschedulethedelivery.
Today,youcancommunicatetorealpeopleusingphone,cellular,orevenemail.Thedeliverynote
shallhandleallofthese:
deliveryNote 1..1
contactRecord 1..n
choice
phone 0..1, class s
cellular 0..1, class s
email 0..1, class s
Adocumentdefinedsimilartoabovecancontainmultiplecontactrecordswhicheachcanbea
phonenumber,acellularphonenumber,orane-mailaddress.Withsuchadefinition,thedifferent
typesofcontactsaresegregatedandthereforecanbebettercontrolled.
Nowthattheformoftheexpecteddeliverynotedocumentisdefined,youhavetosetuptherulesto
generateinstancesofthatdocument.Yournextchallengeishowtospecifywhichoneamong
phone,cellularandemailnodesyouactuallywantintheinstance.
Maybe,yourintuitionwouldtellyoutousetimesdostatementsoneachchildtoalternatively
generatephone,cellularoremail.Thiswontworkintheintegrationengine.Selectioniscentralized
intheintegrationengine:theexpressionattachedtothechoicenodedefineswhichchildto
generateandexpressionsattachedtochildrendeterminetheirvalue.Thefollowingisanexampleof
aMaptogeneratedeliverynotesfromaninputdocument:
phone this\data
cellular this\data
email this\data
Inthatexample,thedocumentfrominputin1containsthenameoftheaddressedcustomerwhile
thecontactinformationiscarriedbythedocumentfromtheinputin2.
ThejoboftheMaphereisto:
l UsecontactTypeIdtodeterminewhichchildtogenerateamongphone,cellularandemail.
l Placeinthegeneratedchildthecontentsofdata.
Totelltheintegrationenginetoselectaspecificchildofachoicenode,youmustuseaselect
statement.Thosestatementsarecomposedofthekeywordselectfollowedbytheindicationof
whichchildtoselectintheformofausualEnglishordinal.
Inthepreviousexample,thecellularnodeisthesecondchildofCHOICE.Tellingintegration
enginetogenerateitisaccomplishedthruthestatement:
select 2nd
ExaminecompletelytheexpressionattachedtotheCHOICEnodeofthepreviousexample:
1 switch (this\contactTypeId)
2 {
3 case 0,1,8:
4 { select 1st }
5 case 10 to 50:
6 { select 2nd }
7 case 99:
8 { select 3rd }
9 default:
10 { exit reject }
11 }
Aswitchstatementstartsatline1.ItteststhevalueofcontactTypeIdtogeneratetheappropriate
child.Whenthevalueis0,1or8,thecontactdataisaphonenumber,thephonechildisgenerated
asstatedbyselect1statline4.Valuesfrom10to50saythecontactisacellularphonenumber,so
line6selectsthesecondchildcellular.Value99meansthecontactisanemailaddress:thethird
childemailisgeneratedasstatedbyline8.
Lines9and10definethebehaviorwhenanunexpectedvalueofcontactTypeIdisencountered.
Inthatexample,anerrorissignaledthrutheexceptionmechanism;havealookatchapterGetting
datafrominput:Pathstonodesonpage59formoreinformationaboutthatconcept.
Theintegrationenginechecksyourexpressionsforactivationofundefinedchildren.Thismeans
youreceiveanerrormessagewheneveryouspecifyanoutofboundsordinalinaselectstatement.
Inthepreviousexample,select 45thisrejectedaswellasselect 101st.Youalsoreceivea
warningforchildrenyourexpressionneverselects.
But,theintegrationengineisnotcleverenoughtodetectpathofexecutioninexpressionsthatdo
notselectatall.Inthepreviousexample,thedefaultcaseoftheswitchstatementdoesnotselect
anythingbuttheexpressioncheckssuccessfully.
Intheexample,sinceanexceptionisraised(interruptingtheexecution),theexpressionexecutes
correctly.Thepathsofexecution,withoutanyselectorexit,leadstoundefinedbehavior.
%text := "";
loop on order:\order\line
{
%text := %text + order:this\qty + " x " + order:this\!item! +
"\n"
};
%text
Insteadofbeingproportionalton,nowthetimespenttoprocessnoccurrencesisproportionalto
n,whichismorepractical.
Inthisexpression,thetextvariableisusedtoaccumulatethefaxtext.Inordertousethisvariable,
youneedtodefineitfirstwithclassS(string).Whenevaluatingtheassignment,theintegration
engineseesthevalueofqtyisneededwhichisawholenumber(classI).Toconcatenatethisvalue,
theintegrationengineimplicitlyconvertsthewholenumberintoastring.
Youcanalsogeneratesetsofoccurrencesfromothersetsofoccurrences.Forexample,youcan
copyorderlinesandaddresslinesfrominputtobillingoutput.
Forcustomerandsupplierlines,yougenerateasmanylinenodesintheoutputasthereexistline
nodesintheinputwiththeinputvaluesinthem.Toaccomplishthis,youuseafor eachdo
structureastheexpressionboundedtolineintheMap:
Thefirstexpressionisforalinenodewhichresidesinthecustomergroup.Thesecondexpression
isforalinenodewhichresidesinthesuppliergroup.
Forlinenodesintheorder,thetechniqueisquitesimilar:youusefor eachontheparentitem.
Whenprocessingthefollowingexpression,thatisattachedtothenodeline(node#33inthe
followinggraphic),theintegrationenginegeneratesasmanyoccurrencesoftheoutputgroupline
asthereareoccurrencesoftheinputgroupline:
Thismeansthatitem(#34),qty(#35)andprice(#36)nodesaregeneratedusingtheir
expressionsintheMap.
Intheprecedinggraphic,youcanseehowthecopyisperformed:
l Theexpressionfortheparentlinecontainsaforeachstatementthatgeneratesasmanygroups
asneeded
l Eachgroupmemberhasanexpressionthatgeneratesitsvaluefromthecurrentlinenodevalue
intheinput(referredtobythekeywordthis)
Noticetheuseofexclamationmarkstokeepthenodenameitemfrombeinginterpretedasthe
keyworditem.
Iftheincomingorderfromthewebserverincludesemptylines(eitheremptyitemsorzero
quantities)andyoudonotwantemptyvaluenodesintheoutputBusinessDocument,addafilter
usingawhereclause:
ThefinalnodethatyouneedtocomputeforbothoutputBusinessDocumentsistheinitialamount
oftheorder.Thisisbasicallythesumofthelinecostsofeachorder,whichforeachlineisthe
quantitymultipliedbytheunitprice.
Youneedtogothroughalltheoccurrencesofline,performthemultiplication,andaccumulatethe
resultsinavariablethatthenrepresentsorderamount.
Thefollowinggraphicillustratesappropriateexpressionboundtotheamountnode:
WhenconceivingDML,Axwaydevelopmentteamsforesawthatwhateverthefunctionalrangeofthe
built-intools,itwouldneverbesufficienttocoveralloftheneedsofeveryuser.ThisiswhyAxway
madeDMLextendable.
Inthischapter,youwillseehowyoucanextendDMLtomeetyourexactneeds.First,youwill
reviewtheconceptofCustomFunctionsandhowtheyareimplementedinDML.Then,youwilllearn
thethreefamiliesofCustomFunctionsthatyoucanusetoextendDML:C-based,SQLandJava-
basedCustomFunctions.
Thischaptercontainstechnicalinformationintendedforadvanceduserswithprogramming
knowledge.
About functions
Intheintegrationengine,buildingMapswithDMLisnotsomuchahardscienceasitisacreativeart
form.YourgoalwithDMListowritethesmallestandmostunderstandableexpressionspossibleto
processyourdata.Thiscanbedifficultwhendealingwithahugeamountofdata.DMLmapping
taskscanoftenberepetitive,withthesamecomplexpatternsrecurringinmanyexpressions.
Intheearlyagesofcomputersciences,therewasnochoicebuttoretypesuchpatterns.Next,most
architecturesprovidedexplicitcallinstructionsthatmadetaskseasier.Insuchsoftwarearchitecture,
oneprogrammightrelyonanotheronetoprovideaspecificservice.Theserviceprovideriscalleda
subroutineorafunction.Subroutinesandfunctionsareindependentblocksofcodethatare
createdonlyonetimeandthenreusedasmanytimesasneeded.
Notonlydosubroutineseliminaterepetitivecoding,theycanalsoorganizemassiveprogramsinto
smallermorestructuredunitsthataremoreunderstandableandeasiertomaintain.
Youvealreadyseenfunctionsearlierinthisguide.Forexample,trimmingandpaddingstringsis
accomplishedusingspecificfunctions.ThesewerepartoftheDMLbuilt-infunctions.Inadditionto
callingthisbasicsetoffunctions,youcanextendtheservicesthatyoumightuseinyourDMLBlock
expressionsbydefiningyourownspecificfunctionswhicharecalledCustomFunctionsinthe
integrationengineterminology.
Callingafunctioninanexpressionisassimpleasquotingitsnamefollowedbythelistofparameters
enclosedbetweenparenthesis.Parameterscanbeexpressionsandareseparatedwithcommas.
Asanyintegrationengineobject,CustomFunctionsarereferredtousingeitherafully-qualified
nameorashortname,shownasfollows:
myentity.commonstuff\calendar.IsLeapYear(%year)
commonstuff\calendar.IsLeapYear(%year)
IsLeapYear(%year)
Youhavealreadyseenexamplesoffunctioncallspreviouslyinthisguide:
Thisisacalltothebuilt-infunctionremainderthatdividesitstwoparametersandreturnsthe
remainderofthisdivision.
Defining a function
BeforeyoucanuseaCustomFunction,youneedtoinformtheintegrationenginethatsuchanew
functionexists.ThistaskiscalledfunctiondefinitionandisaccomplishedinAxwayMapping
Services.
WhendefiningafunctioninAxwayMappingServices,youcreateanewobjectwithinanentityand
folder.Themainpurposeoffunctiondefinitionistoinformtheintegrationengineabout:
l Thenametobeusedtocallthefunction
l Thenumberandtheclassesofargumentspassedtothefunction
l Theclassofthevaluereturnedbythefunction
Unsimilartobuilt-infunctions,thenamesofyourCustomFunctionsmuststartwithcapitalletters.
Allofthecodethatdetermineswhetherayearisaleapyearornot,residesinaCustomFunctionthat
isnamedIsLeapYear.Intheprecedingexamples,youcanseevariouscallstothatfunctionusing
completeorshortnames.TherulesfornamingtheCustomFunctioninAxwayMappingServicesare
thesameasforotherAxwayMappingServiceso bjects.FordetailsrefertosectionNamingobjectson
page32.
TodefinetheIsLeapYearCustomFunction:
1. InAxwayMappingServicesworkbench,intheleftframe,selecttheExtended Objectsfolder
andthentheFunctionssubfolder.
2. Usethecontextmenutocreatethenewfunction:
3. Fromthecontextmenu,yougetthefollowingwizard:
4. Followthewizardandchoosethecategoryofthefunctionandafternextthenameofthe
function.ClickonFinish.
5. IntheParameterstab,thatyoucanaccessbydouble-clickonthenewfunction,definethe
functionparametersifneeded.
6. Eachlineinthelistdefinesaparameter:youmustnameeachparameteranddefinetheclass
expected.Intheexampleabove,onlyoneparameterisdefinedwhosenameisyearandthat
acceptsawholenumbervalue(classI).
7. Closethewindowandconfirmmodificationbysaving.
Thelistofparametersyoudefinehereiscommonlyknownasthelistofformalparameters.When
theintegrationengineevaluatesanexpressioncontainingacalltotheCustomFunction,itreplaces
eachformalparameterbythevalueofthecorrespondingexpressionyoustateinthefunctioncall;
thesearecalledrealparameters.Inthefollowingexpression,theexpression%year + 8adds8to
thevalueofthevariableyear:
IsLeapYear(%year + 8)
TheresultisarealparameterofthecalltofunctionIsLeapYear.Thisfirstrealparameterisbound
totheformalparameteryearwhichisdefinedinthepictureabove.Basically,formalparametersare
function-related,whilerealparametersarecaller-related.
AftertheCustomFunctiondefinitioniscomplete,youcanusethisCustomFunctioninyour
expressions:theintegrationengineacceptsexpressionswithcallstoIsLeapYearwhenchecking
yourwork.
YoucanplacecallstotheCustomFunctionsyoudefinedinanyDMLBlockexpression.Youinform
theintegrationengineserverofthekindofvalueyourCustomFunctionreturns(usingtheClass
fieldoftheGeneraltab)andwhatvalueitcanacceptforparameterexpressions.
Thismeansthatyouhavecertainuselimitations:thefollowingtablelistsexamplesofacceptable
andunacceptablecalls:
4*IsLeapYear(1987) OK ClassBofthevaluereturnedbythefunction
canbeconvertedtoclassItoperform*.
Declaring a function
Definingafunctionisnotinitselfenoughtomakesomethingappropriatehappenatthetimethe
integrationengineserverprocessesthefunctioncall.Sofarallyouhavedoneistoindicatethata
functionnamedIsLeapYearcanbecalledalongwithrequirements,fromyourexpressions.
Whentheintegrationengineperformsafunctioncall,itfirstevaluatesthevaluesofthereal
parameters,thensuspendstheevaluationoftheDMLBlockexpressionandhandsoverprocessing
controltothecalledCustomFunctionitself.Thefollowingdiagramillustratestheprocessing
sequence:
WhentheCustomFunctioncompletesprocessingandreturnsavalue,thisvalueisusedtocontinue
theevaluationintheexpressionfromwhichthecallwasmade.Theredsectionofthepreceding
graphicrepresentstheCustomFunctioncodeblockthatsuppliestheservice,thisblockiscalledthe
implementation(orbody)ofthefunction.
Declaringafunctionistheprocessofwritingtheimplementationofthefunction.Implementations
ofCustomFunctionsarenotDMLexpressions:towritesuchbodiesyouneedarealprogramming
languageandpossiblyextralibraries.MostofthetimedeclaringaCustomFunctionisaccomplished
usingthirdpartytools.
Unexpectedly,youcanuseanyprogramminglanguagetoimplementaCCustomFunction,
provideditcomplieswiththeCcallingconventionandthestandardABIforthehostonwhichthe
integrationengineserverruns.Thebasicservicesthatyouneedforembeddingyourfunctioninto
thewholeintegrationengineserveraresuppliedasaC-languageAPI.
Getting an overview
ThebasicstructureofaCustomFunctionwrittenusingCprogramminglanguageisshowninthe
followingdiagram:
Envelopingthecodethatperformsthecoreprocessingcodeofthefunctionaretwolayersthat
extractthevaluesoftherealparametersandgeneratethereturnvalue.Thesearenecessarybecause
oftheuseinintegrationengineofabstractcontainersforparameters.
ConsidertheIsLeapYearCustomFunctionwhichdetermineswhetherasuppliedyearisaleapyear
ornot.TheCprototypethatmatchesthedefinitionmadepreviouslyis:
ThefirstargumentofaCustomFunctionisalwayshCtx,whichshouldbepassedwithoutany
changetoallsubsequentcallstotheintegrationengineruntimeserviceslibrary.Theremaining
argumentsarethefunctionreturnvalueanddefinedparameters.Eachoftheseisahandleson
containerthatcontainthevalues.
Thefollowingtabledescribesthematchingbetweentheclassandthewriteandretrievefunction
names;thestandardCtypethatcorrespondstotheclassisalsoshown:
Retrievefunctionsforscalartypes(B,I,RandDclasses)allfollowthesamesignaturemodel:
Retrievingstringsorraw-dataarisestheproblemofallocatingenoughroomtoreceiveacomplete
copyofthedateread.Afunctionisprovidedthatreturnsthememorysize(inbytes)neededtohold
theretrieveddata:
Thisfunctioncanbeappliedtoanycontainerandreturnsasizeinbytes.Thefollowingtableshows
sizesreturnedbythiscallinseveralsituations:
SunSolaris B 4.
Thisplatformconsiders32bitintegers
Win32 I 4.
32bitswindowsencodeslongintegerson32bits
HPItanium64 I 8.
Thisisa64bitplatformthatencodesintegerson8
bytes
any S thenumberofUTF8bytesrequiredtoencodethe
textplusone.
Thefunctionneverreturnsthecharacterslengthof
thestringbecausethislogicalsizeisuselessfor
bufferallocation.Oneextrabyteisreservedfor\0
terminator.
any V theexactnumberofbytesheldinthecontainer
Toretrieveastringfromacontainer,youmustfirstallocateamemorybufferlargeenoughtohold
thecompletestring.Then,youusexibrt_getStringtoclonethestringheldinthecontainerinto
thebufferyousupplied.
Thefollowingisatypicalpieceofcodethatextractsastring:
nBytes = xibrt_getSize(hCtx, hRegister);
pszString = calloc(nBytes, sizeof(char));
if (pszString != NULL && nBytes > strlen("change"))
{
nCopiedBytes = xibrt_getString(hCtx, hRegister, nBytes,
pszString);
}
Bothstringandraw-dataretrievingfunctionsusethesamemodelasfollows:
Inbothcases,yousupplythereceivebufferaddress(pszTargetandpTarget)anditsavailablesize
(nTargetSize).Thissizecanbemoreorlessthanrequired.Bytesfromsourcecontainerwillbe
copiedthereuntilallavailableroomisexhausted.Thiscallcannotoverflow.Theactualcountof
copiedbytesisthenreturned.
Asthelastargumentnameofxibrt_getStringsuggests,stringsarealwaysretrievedusingUTF8
encoding.Asaconsequence,eachcalltoxibrt_getStringmighttriggerthecharacter-set
conversionengine.WhendesigningyourCustomFunctions,becarefulnottoperformtoomany
character-setconversionsbecausethisisahightimeandresourcesconsumingtask.
Considerthefollowingexample.YouwanttodesignaDMLBlockthatcheckswhetherIBAN
numbersfrombankingtransactionsarelegal.IftheIBANisnotvalid,aquestionmark(?)is
appendedtothatcodewhileaplus(+)isaddedotherwise.Youimplementthecheckand
modificationinaCCustomFunction,asfollows:
/* Allocate buffer for modified IBAN */
nBytes = xibrt_getSize(hCtx, hIBAN);
pszIBAN = calloc(nBytes + 3, sizeof(char));
/* Collect the IBAN from its container */
xibrt_getString(hCtx, hRegister, nBytes, pszIBAN);
/* Check IBAN and append appropriate marker */
if (myIBANCheckRoutine(pszIBAN))
{
/* IBAN is OK, append '+' */
strcat(pszIBAN, "+");
}
else
{
/* IBAN is KO, append '?' */
strcat(pszIBAN, "?");
}
xibrt_setString(hCtx, hIBAN, nBytes + 1, pszIBAN);
Thiscodecanbeverytimeconsuming.IfyourIBANstringsareencoded,forexample,inEBCDIC,
theintegrationengineconvertsthemtwice:
l FromEBCDICtoUTF8whenthestringisretrievedusingxibrt_getString
l FromUTF8backtoEBCDICwhentheedstringisgivenbacktohIBANusingxibrt_setString.
Thepreviouspieceofcodeusesoneofthewritefunctionsthatplacesdataintoanexisting
container.Asexpected,writerfunctionsforscalartypesarenatural:
Concerningwriterfunctionsforstringsandraw-data,youmustsupplyabufferaddressandthe
lengthofsignificantdataitcontains,inbytes:
Afteragain,thesystemassumesthesuppliedstringisUTF8encoded.
Thesourcelengthcanbelessthantheactualsourcebuffersizebecauseonlysignificantdata
(includingfinal\0forstrings)isconsidered.
Whenretrievingvaluesalwaysbesurethatthecontainerdoesnotholdasymbolicvalue.Acallto
xibrt_isNullorxibrt_IsAbsentisalmostmandatorybeforecallinganygetterfunctionbecause
gettersreturnirrelevantvalueswhenthecontainerholdseithernullorabsent.
Detecting errors
Thefunctionsdescribedpreviouslyinthischaptermightonlyfailuponclasscontainermismatch,
forexampleifyoutrytocallxibrt_setBooleanonacontainerthatholdsaclassSvalue.Insucha
situation,thecallisabortedandnoactionisperformedatall:neithervalueretrieval,norcontainer
update.
IfyouwriteyourCustomFunctionscarefully,thatkindoferrorshouldnothappen.Sinceyoudefine
theclassesforallargumentstoyourCustomFunctions,youalwaysknowtheexacttypeofdataheld
bycontainers.
TokeeptheintegrationengineruntimeserviceslibraryAPIassimpleaspossible,errordetectionis
notcarriedbythecallthemselves(noerrorcodereturned).Toknowaboutthelastcallstatus,just
callthefollowingfunction:
Thiscallreturnsoneofthefollowingvalues:
Value Circumstances
XIBRT_SUCCESSFULL Thepreviouscallwascompletelysuccessful
XIBRT_CLASSMISMATCH Thecalloperatesonacontainerwithan
appropriateclass
XIBRT_NULLVALUE Attempttoretrievevaluefromacontainer
containingnull
XIBRT_ABSENTVALUE Attempttoretrievevaluefromacontainer
containingabsent
Eachcalloverwritesthelaststatus:ifyoumissedanerrordetection,theresultislost.
Environment considerations
Thesubdirectoryc/includesofyourintegrationengineserverinstallationholdstheheader
XIBRT_Interface.hthatcontainsalldeclarationsneededtouseruntimeserviceswithinyour
CustomFunctions.
Onlyoneheaderinclusionisrequired.Thisheaderhasnodependencieseitheragainstanother
suppliedheaderoranysystemheader.Theonlyrequirementisthefollowinglineinyourcode:
AllthesefunctionsarecontainedinadedicatedsharedobjectnamedlibXIBrt.soonUnices,and
libXIBrt.dllonWindows,whichresidesinthebinsubdirectoryofyourintegrationengineserver
installation.
WhenbuildinglibXIBcf.soyoumustlinkwithlibXIBrt.soandanyoftherequiredthird-party
libraries.RememberthatlibXIBcf.sowillbeloadedonlywhenrequired:nocalltouser-defined-
function,nolibraryloading.YourlibraryforCustomFunctionsmustbeloadablebyimplicitdynamic
link.itisagoodpracticetoplaceitintothebinsubdirectoryofyourintegrationengineserver
installation.
Thiscanbebothcomplexandrisky,andmightrequirealargeamountofobscurecode.Forvery
simplequeries,theintegrationengineprovidesaquicksolution:SQLCustomFunctions.
SQLCustomFunctionsperformSQLselectionqueries.TocreateanSQLCustomFunctionyoubegin
bycreatinganewCustomFunctionobjectinAxwayMappingServices.
UnsimilartoCustomFunctionsimplementedinC,SQLCustomFunctionsaredefinedanddeclaredin
AxwayMappingServices:nothird-partytoolsetisrequired.Asaresult,whenyouselectSQLasthe
CustomFunctioncategory,AxwayMappingServicesd isplaystheImplementationtab.
IntheEditorviewofthefunction,entertheSQLstatementthatyouwanttoperform.The
statementmustbeasimpleSELECTstatementthatreturnsonlyonecolumnfromonerow.The
maximumlengthoftheSELECTstatementis5,000characters.
ThevaluethatyourSQLCustomFunctionreturnsmustbecompatiblewiththeclassyouselectforit.
Ifthestatementreturnsnoneormorethanonerow,youwillobtainanerror.Inaddition,whena
statementreturnsanSQLnullvalue,yourfunctionwillreturnasymbolicnull.
TheparametersofyourCustomFunctioncanbereferredtointheSELECTstatement.Todothis
youenclosetheparameternamesbetweenhashes#.Forexample,imagineatableZIPcontaining
twocolumns:oneforcitynames(CITY)andthesecondforzipcodes(CODE).Toimplementthe
GetZipCodeCustomFunctionthatreturnsthecodeofasuppliedcity,usethefollowingquery:
WhentheintegrationengineexecutestheCustomFunction,itreplaces#city_name#withthe
valueofthefunctionparametercity_nameenclosedindoublequotes,andreturnsthevalueofthe
codefromthetable.
ThefollowinggraphicillustratesthecontentoftheImplementation tab:
Forsuchfunctionstobesuccessfullyexecuted,youmustdefineaJDBCChannelinAxwayMapping
ServicesthataddressestheappropriateDBMS.
Basically,thebodiesofyourownfunctionsareanimplementationoftheFunctioninterfacethatis
suppliedwiththecom.axway.xib.api.dml.Functionpackage.Whenwritingthebodyofyour
JavaCustomFunction,youcreateanewclassthatimplementstheinterfaceandcontainsamethod
forthebodyofyourfunction.
ThefollowingisapieceofJavacodefortheIsLeapYearCustomFunction:
import com.axway.xib.api.dml.Function;
Insuchafunctionyoureceivethefunctionparametersintheargsarray.
Thisarraycontainsoneobjectforeachparameter.Thefollowingtableshowstheclassofthe
receivedobjectinconnectionwiththeclassoftherealparameter:
Class of Class of
the parameter the received object
I java.lang.Boolean
I java.lang.Integer
R java.lang.Double
S java.lang.String
D java.lang.Date
V byte[]
Wheneveroneoftheparametersholdsasymbolicvalueabsentornull,youreceivetheJavanull
valueinsteadofanobject.YoumightusethisnulltomaketheCustomFunctionreturnthe
symbolicvaluenull.ReturningthesymbolicabsentisnotpossibleforCustomFunctionswrittenin
Java.
Afteryouvewrittenyourfunction,youusetheJavacompilertocompileit:
Asshowninthecommandabove,thecustomfunctionsAPIisprovidedthroughaspecificjarfile
thatmustbeincludedintheclasspath.Thatfileissuffixedbyitsrevisiontagintheformx.y.z.
AllthecompiledobjectsfortheCustomFunction,includingthepossibledependencies,canbe
placedinanylocationavailabletotheintegrationengineserverhostfilesystem.
Youhave,however,tobuildamanifestfile,makeitsClass-Path propertypointtotherequired
places,andincludeitinajarin$CORE_ROOT/local/java/dmlfunctions.Youaretotallyfreein
choosingthenameofthejarfileandtoplaceasmanyfilesasneededinthatdirectory.
WhenyoudefinetheCustomFunctioninAxwayMappingServices,donotforgettoselectJavain
theCategoryfieldoftheGeneraltab.Thenenterthenameoftheclassandanameofthefunction
fortheimplementation.
Theonlyremainingtaskisthepartnerratesfeeding.IfyoureferbacktochapterIntroducingDMLon
page9,youllseethatthisfeedinginvolvesanetworkofDMLBlocks.
ThefirstDMLBlock(MB_tableLoader)isactivatedbyastarteventthatistriggeredeachtimea
newmessageisfedtotheDMLBlockinput.TheDMLBlockloadstheXMLfilethatcontainstherates.
ForthisDMLBlockyouneedtodefineonlyaDecision-PaththatactivatesaMap.ThetaskoftheMap
istoloadthefileintotheVclassnodeoftheoutput.
ThisMapusestheLoadFileCustomFunctiontoaccomplishtheloadingtask.Basically,thisCustom
Functionopensafile,placesthefilecontentintothereturnedVvalue,andthenclosesthefile.If
thefileisnotfound,theCustomFunctionreturnsabsent.
LetshavealookattheCcodethatperformsthistask:
fclose(pFile);
AfteryouvecompiledthiscodecompiledanddefinedtheCustomFunction,thefunctionis
operationalandcanbeusedatruntimetoloadyourfile.Thesecondstageofthefeedingis
accomplishedbyanotherDMLBlock(MB_tableBuilder)thatparsestheXMLfileandgeneratesthe
correspondingBusinessDocument.
IntheDecision-PathoftheMB_tableBuilderDMLBlockyoucreateaparsestepthatgeneratesa
BD_partnerRatesBusinessDocumentinstancefromtherawdatanodeoftheinputBusiness
Document:
Now,yourMB_extractorDMLBlockiscorrectlyfedwiththepartnerrates.Theprojectiscomplete.
ThischapterdiscusseshowtohandleexceptionaleventswhenmappingdatainDMLexpressions.
Basicallyanexceptionisanalarmthatissetoffwhensomethingunusualhappens.Youstillneedto
useaconditionalstatementtodetecttheevent,butwhentheconditionismet,theintegration
engineraisesthealarm,abortstheprocessingoftheinputdataandeitherdiscardsorrejectsthe
dataithadjuststartedtocompute.
Settingoffthealarmisknownasraisinganexceptionandisdonebyinvokingthespecial
instructionexitwithasingleargumentthatstateswhichbehaviortheintegrationenginemustadopt
tohandlethealarm:
reject Whenreceivingthisexception,theserverabortsthecurrent
processinganddirectlygoesonthenextone.
rejectMessage Theintegrationengineserverrejectsthemessagecurrentlyprocessed,
theneitherwaitsorprocessesthenextincomingmessage
Hereisanexampleofanexpressionthatrejectsamessageonacertaincondition:
if CheckIBAN(this\\IBAN_Code) then
{
exit rejectMessage
}
Wheneveranexitisencounteredandexecuted,theserverabortswhatitwascurrentlydoing.
Usually,thisleadstothecancellationofseveralpartsofthecurrentdataprocessing.Exception
handlingreliesonacompletetransactionalenginethatisabletovalidateorcanceldatageneration
operationsaccordingtothesituation.
Thefollowingdiagramshowshoweventstakeplaceinthewholeprocessofinputdataandoutput
generation.
Startandendeventsaretypicallyusedeithertoparticipateinenvelopegeneration(forexample:the
starteventgeneratesthefinalmessageheaderwhiletheendeventbuildsthefinalmessagetrailer)
orforloggingpurposes(tokeeptheuserinformedoftheprogressoftheprocess).
YouuseerroreventstorecoverfromerrorconditionsusingDMLcode.Forexample,youcanusean
erroreventtoextracterroneousdatafromthemaindatastreamandsendittoaspecialoutput.Error
eventsprovideanextensionofsomeaspectoftheregulardataprocessing.Thisiswhy,inthe
diagramabove,theyaresymbolizedusingthesamecolor.
Asthediagramsuggests,withaMappingFlowandanerroreventappropriatelydefined,youare
abletoprocessspecificallyfaultypartsoftheinputdatawhilenormallyprocessingtheotherparts.
Whenthebadpartisprocessedanerrorconditionisdetectedandcontrolistransferredtotheerror
event.Whenthiserroreventhasbeenexecutedandprovidedtheerrorrecoveringisactive,control
istransferredbacktotheregularprocessingchain.
Severalfamiliesofsituationsleadtoanerrorconditionandtriggertheerroreventwhendefined:
Agoodexampleofatransactionisthetransferoffunds,letssay500USD,fromacustomer's
savingsaccounttoacustomer'scheckingaccount.Fromthebankpointofview,thisisasingle
operation,butitinvolvesatleasttwoseparateactions:debitingthesavingsaccount,andcrediting
thecheckingaccount.Ifeitheroneoftheseactionsdonotsucceed,thebooksofthebankwillnot
balanceattheendoftheday.Aggregatingbothactionsintoasingletransactionensure
consistency:thewholetransactioniscanceledifeitheroneoftheactionfails,thewholetransaction
iscompletedifbothactionssucceed.
TheprocessinginaMappingFlowiscomposedofatleastthreetransactions:
l Starttransactionthatcoverstheoperationsperformedbythestartevent
l Instancetransactionwheredataprocessingtakesplaces
l Endtransactionthatiscomposedofend-eventactions
Thesethreetransactionsareindependentofeachother:datageneratedbythestarttriggerissentto
outputwhenevertheinputdataprocessingcompletessuccessfullyornot.
Furthermore,inputdataprocessedbytheMappingFlowcanbecomposedofseveralchunksofdata
calledinstances.Usually,allinstancesareprocessedwithinasingletransaction(theinstance
transaction)butwhenerrorrecoveringisactive,atransactioniscreatedforeachprocessed
instance.ErrorrecoveringisafeatureoftheMappingFlowthatyouactivatebycheckingcontinue
on errorintheFlow propertieswindowintheAxwayMappingServices.
Thefollowinggraphicshowswhentransactionsarestarted,completedorcanceledinseveral
situations:
Althoughallsituationsinthisgraphicshowbothstartandendtransactions,thisisnotmandatory:
starteventsandendeventsareoptional.
Anotherkeypointinthisdiagramisthewaytheerroreventacts(situations4and5).Whentheerror
occurs,thecurrentinstancetransactioniscanceled.Inthosesituations,onlyoperationsrelatedto
theprocessingofinstance#2arediscardedbecauserecoveringisactive.Then,theoperations
relatedtotheerroreventareperformedaspartofthecurrent,andthereforeemptyinstance
transaction.Accordingtotheresultsoftheerrorevent,theseoperationsmightbecompleted
successfullyor,again,canceled.
Basically,actionsperformedbytheengineinsideatransactionareoutputdatageneration.Whena
transactioniscompleted,outputdataiskeptinapermanentstorageareawiththeaimofbeingsent
tothenextactivity.
Theactionofcompletingatransactioniscalledcommitting (orsimplycommit)incomputer
terminology.Theoppositeaction,thatcancelsatransactionandthereforedestroysgenerateddata,
iscalledrollingback(rollback).
l Alloperationssucceed,theDMLBlockexecutioniscompletedsuccessfully.
l Somethingfailed,anerrorisdetected.
l rejectexceptionisraisedbecauseexit rejectwasexecuted.
l rejectMessageexceptionisraisedbecauseexit rejectMessagewasexecuted.
BothrejectandrejectMessageexceptionsleadtotransactionrollbackandmighttriggertheerror
event.Themaindifferenceliesinthescopeoftherollback.
Thescopeoftherejectexceptionisalwayslimitedtothecurrenttransaction.Whenraisedindata
processing,onlyactionsperformedwhilemappingthecurrentinstance(ifrecoveringisenabled)or
thecompleteinputmessage(ifrecoveringisdisabled)arecanceled.Operationsrelatedtostartand
endeventsareoutofscope.
Withthisexception,theerroreventistriggeredifdefinedandthencontrolistransferredbackeither
totheprocessingofthenextinstance,whenrecoveringisenabled,ordirectlytotheendevent.If
noendeventisdefinedwhilerecoveringisdisabled,thewholeprocessisfinished.
Usedinconjunctionwitherrorrecovering,therejectexceptionmightleadtotheacceptanceofthe
inputmessagewiththesegregationbetweencorrectandfaultyinstancesitcontains.Whenerror
recoveringisdisabled,theinputmessageisalwaysrejected.
TherejectMessageexceptionscopeisalwaysglobal:whereverandwheneverthisexceptionis
raised,allactionsrelatedtotheprocessingofdatacontainedintheinputmessagearediscarded.
Althoughstartandendtransactionsarestillsegregated,theraiseofrejectMessagewillcancelall
instancetransactions.
Asaconsequence,whenerrorrecoveringisenabled,aglobalrollbackoperationmightbe
performedthatrollsbacktransactionsrelatedtoeachalreadyprocessedinputinstances.Insuch
situation,instancetransactionsaredistinctbutboundtogetherandthereforerolledbackasa
whole.
Unliketoreject,therejectMessageexceptionalwaysrejectstheinputmessage.Whenoccurring
inthestartevent,noinputdataisprocessed:controlisdirectlytransferredtotheendeventif
defined,ordirectlyfinishedotherwise.
Withmultiplesituationsandactions,thebehavioroftheengineisquitecomplextodescribe.The
followingdiagramtriestomakethingsclearer:
Inthisdiagram,theprocessbeginsandendswiththedouble-circlestepsstart,message
acceptedandmessage rejected.Blueboxessymbolizetheexecutionofsub-networksofDML
Blocksthatarerelatedtoeventsordataprocessingmainstream.
Commitandrollbackactionsarepicturedwithgreenandbrowncircles;theyusuallyoperateonthe
currenttransaction,exceptforglobal rollbackthatcancelsallinstancetransactionswhenerror
recoveringisenabled.
Theemptybluecircleisthereforeaseofreading:itconcentratesseveralincomingpathsbeforethe
definitionoftheendeventisdetermined.
WhenusingClanguage,asetofdefinesisprovidedthatrefertoeachexception:
XIBRT_SUCCESS noexceptionraised
XIBRT_SYSFATAL asystemerrorisdetected
XIBRT_REJECT_MESSAGErejectMessage exceptionraised
XIBRT_REJECT_INSTANCErejectInstance exceptionraised
ForCustomFunctionswrittenusingJavaprogramminglanguage,raisingtherejectMessage
exceptionisaccomplishedbythrowingaFunctionExceptionobjectwithitsinternalcodesetto
CUSTOM_EXCEPTION.
WhencodingtheCustomFunctioninCprogramminglanguage,exceptionswerehandledusing
nullorabsentsymbolicforthereturnedvalues.Suchmanagementdoesnotdistinguishbetween
emptyornon-existentfilesandtechnicaldifficultiesinloadingapresentandfullfile.
Amoreaccurateprocesswould:
l Returnabsentwhenthesuppliedfiledoesnotexistorisempty
l Returnnullwhenthesuppliedfilenameisabsentornull
l Signalasystemerrorwhenthefunctionisnotabletoloadthefilefortechnicalreasons.
LetsreworkthecodeforLoadFile:
if (!pBuffer)
{
return XIBRT_SYSFATAL;
}
ulSize = fread(pBuffer, 1, ulSize, pFile);
fclose(pFile);
Intheprecedingcode,partsthatneedtobechangedoraddedareframedinorange.Thefunction
nowraisesanexceptionwhenitdetectsanabnormalsituation.Thismighteitherinterruptthe
processingofthecurrentdocumentoraborttheintegrationenginetasks.
YoumightreuseyourLoadFileCustomFunctioninotherprojects.Thisiswhyyouhaveitreturn
absentwhennofileisfound.Insomeprojects,youcandealwiththisabsentvalue;imaginethat
thecontentsofthefilearesimplycopiedinanoptionalnode:nofilemeansnooccurrenceofthe
node.
IntheFoodBrokerproject,non-loadingofthepartnerratesresultsinnoprocessingatall.Therefore,
youmightwanttorejectmessagesassoonasyoudetectthattheratesarenotavailabletoyour
system.
ThisdetectionisaccomplishedwhentheLoadFileCustomFunctionreturnsabsentvalue.Inthis
caseyouneedtoraiseanexceptionthattellstheintegrationenginetorejectmessagesfromtheweb
server.ButraisingrejectMessageduringthefeedingoftheratesisnotappropriate.Thismustbe
donewhileprocessingdatafromyourMappingFlowinput.
Youfaceonedifficultyhere:thedetectionofunexpectedbehavioroccursinadifferentplacethan
theonewhereyouraisethealarm.,youneedtopropagateyouralarmsilentlyusingtheabsent
valueuntilyoureachtheappropriateexceptiontriggerpoint.
Thefollowinggraphicillustratesthisstrategy:
Tosilentlypropagatethedetectedproblem,youmustbeabletoprocesstheabsentvalueinboth
theMB_tableLoaderandMB_tableBuilderDMLBlocks.Intheformer,thevaluereturnedby
LoadFileisalwaysplacedintheoutputBusinessDocument,evenifthatvalueisabsent.Inthe
later,insteadofusingtheparsestep,anemptyoutputBusinessDocumentisgeneratedusinga
dedicatedMap.
TheMR_generateEmptyMapgeneratesaBusinessDocumentthathasonlyoneoccurrenceofthe
nodepartnerwhichgroupsbothnamesandratewithanabsentvalue.
Then,intheMB_extractorDMLBlock,thefirststepoftheDecision-Pathcheckswhetherthe
documentthatcomesfromratesisfullornot.Ifnot,anexitstepistriggeredthatraisesthe
rejectMessageexception:
TheexpressionboundtothefirstifstepinthisDecision-Pathistruewhenevernooccurrencesof
nodepartnerexistintheinputBusinessDocument,orwhenatleastoneofthenodesnameor
rateisfoundwithanabsentvalue.
Use restrictions
AlthoughmostDMLinstructionsandoperatorscanbeusedinanyexpression,certainrestrictions
exist.ThefollowingtablesummarizeswhereyoucanuseDMLelementsandwhereyoucannot.
literals
variablereading
variableassignment
explicitvalueassignmentusing$
+,-,*,/and**onnumbers
+and*onstrings
nodepaths
and,or,xorandnot
ifthenelsestatement
switchstatement
definedandundefinedoperators
loop onstatement
select statement
tree statement
exit statement
Quick-Reference
ReferenceinformationaboutDMLlanguageyoufindintheDMLReferenceGuide.
ExamplesofsuchadditionalinformationarethepartnerratesinyourFoodBrokerproject.Youcan
imaginemanymoreexamples:thelistofcurrencyexchangerates,atablefortaxrates,alistof
customeridentifiersInallthesecases,theadditionalinformationthatyouneedissimilartoa
dictionary,you:
l Knowthepartnernameandyouaresearchingfortherelatedrate
l AredealingwithanamountinSwissFrancs(CHF)andwanttoknowtheratetoobtainDollars
(USD)
l Knowthetaxcode(1,2,3)andyouneedthecorrespondingrate
Havethecustomer'snameandyouneeditsinternalid
Inallthesesituations,theinputprovidesakeythatyouusetosearchforadditionalinformationthat
relatestothatkey.
Intheintegrationengine,youcandefineandusesuchdictionaries.EachintegrationengineTable
Objectisastorageareainwhichdataisorganizedintabularform.Whendefiningatable,you
createasmanycolumnsasyouwant.Foreachcolumn,youselectwhetheritisakeycolumnora
valuecolumn:
l Keycolumnsareusedtoselectonlyasignificantrowamongallexisting;intheprevious
examples,thepartnername,thecurrencynameorcode,thetaxcodeorthecustomernameare
keycolumns.
l Valuecolumnsc ontainthedataboundtothekeysthatyouwanttoretrieve;intheprevious
examples,thepartnerrate,thecurrencyrate,thetaxrateorthecustomeridarevaluecolumns.
Inadditiontokeysandvalues,theintegrationengineautomaticallydefinestwocolumnsthatstate
theperiodduringwhicheachrowisvalid;theseareStart DateandEnd Date.
Todefineatable:
2. WhenyouselecttheTable command,awizardforcreatinganewtableobjectopens.Typein
thenameforthenewtable.ClickonFinish tocreatethetable.TheTableeditoropens:
UsetheNamefieldtosetthenameofthecolumnandtheLabelfieldtodefineanoptional
detaileddescriptionofthecolumncontents.Youmustselecttheclassforthevalueofthe
column.Ifyouwanttodefinetocolumnasakey,justselecttheKey Columncheck-box.
6. Toaddlines(orrows)inthenewtable,clickthefirstbutton(greenplus)ofthetoolbaratthe
rightsideofthelistview.
Anewlineinthemainframeappears.Inthisnewlineyoucanenterthevaluesofeachcolumn.
ThetabledefinedaboveisasubstitutetotheXMLfileforpartnerratesinthisFoodBroker
example.Eachrowrelatestherate(Rate)forapartnerwithitsname(Name).
7. Checkandsavetheobject.
ThecolumnsandlinesthatyoudefinedinAxwayMappingServicesareimmutableduringdata
generation.IfyouneedtoalteratableyouhavetouseAxwayMappingServices.DMLisreservedfor
tablereading .InDML,youhavefunctionstocheckwhetheratleastonelineexistsinagiventable
thatmatchesasetofkeys.Hereisanexample:
ThefewlinesabovecheckwhetheralineexistsfortheJaleo partner.ThefunctionIsKeyPresent
returnstrueifsucharowexistsandfalseotherwise.TheveryfistargumentofIsKeyPresentis
thenameofthetableandcanbefullyqualifiedorabbreviated.Theremainingargumentsarethe
valuesforthekeysfollowingtheorderdefinedinAxwayMappingServices. Considerthefollowing
tabledefinedinAxwayMappingServices:
Tocheckwhetherarowexistsinthistable,yourcallstoIsKeyPresentmustcontainreal
argumentsforeachofthethreedefinedkeys:
%has_rate := isKeyPresentInPeriod(TBL_PartnerRates,
"Bombay Club Restaurant",
'2007-10-9')
setsthevariablehas_ratetotruebecausetheperiodbetweenStartDateandEndDateofthe1 st
lineofTBL_PartnerRatescontainsOct 9 th, 2007.
YoucanalsoextractvaluesfromatableusingcallstoreturnColumn asfollows:
AsforisKeyPresent,argumentsarethenameofthetablefollowedbythekeyvalues.Then,when
yourtablecontainsmorethanonevaluecolumn,youmustappendthenameoftheonethatyou
want.
WhenacalltoreturnColumnisevaluated,theintegrationenginegoesthroughthespecifiedtable
tofindthefirstrowwhichmatchesthespecifiedkeys.Ifnomatchisfound,thecallisevaluatedto
absent.
Message attributes
Intheintegrationengine,dataispassedfromactivitytoactivityintheformofmessages.These
messagesareparsedtobuildBusinessDocumentinstancesthatareusedasDMLBlocksinputs.DML
Blocks,inturn,generateBusinessDocumentinstancesthatareincorporatedinmessageswhichare
sentoutsidethesequentialactivity.
Theintegrationenginemessagesaresimilartoordinarymail:theyincludeboththeactualdata(the
lettertext)andinformationtohelpmessagedelivery(theenvelope).Intheintegrationengine
terminology,theenvelopeinformationiscalledmessageattributes.
Messageattributesaresegregatedintwocategories:systemattributesanduser-definedattributes.
Systemattributesareusuallyboundtoreceiveandsendactivities.Forexample,anFTP Receive
Activityautomaticallyfillsthefollowingattributes:
Use_Host I UsethecontentsofHostattribute
Host S RemotehostIPorDNSaddress
Use_Port I UsethecontentsofPortattribute
Port S RemoteFTPport
Use_User I UsethecontentsofUserattribute
User S Remoteusername
Use_Password I UsethecontentsofPasswordattribute
Password S Passwordforremoteusername
Use_Account I UsethecontentsofAccountattribute
Account S
Use_Script I UsethecontentsofScriptattribute
Script S FTPScripttoexecute
Use_Timeout I UsethecontentsofTimeoutattribute
Timeout I Connectiontimeoutvalue
Use_RemoteFileName I UsethecontentsofRemoteFileName
attribute
RemoteFileName S Filenameonremotehost
User-definedattributesaredefinedfollowingyourneedsandarethefavoredwaytotransmitextra
datafromoneactivitytoanother.Todefineanewattribute,youmustcreatean.sh4fileinthe
$(CORE_LOCAL)/config/attributedirectoryonyourintegrationengineserver.
Whateverthenameofthisfile,theintegrationenginecollectsallthedefinitionsinalltheexisting
.sh4filesofthissubdirectorytocreatethecorrespondingmessageattributes.Allofthesearemade
availableglobally,thatisforanymessagecarriedfromanyactivitytoanyotheractivity.
Thefollowingisanexampleofsuchafile:
Thisexampledefinesamessageattributenamedfoowithafieldnamedbar.Thisfieldholdsa
string.
Afamilyofbuilt-infunctionsexiststoreadattributes.Sinceyoumightrequireaspecificclassforthe
result,thereexistfourfunctionsinthisfamily:oneforeachclass(getBooleanAttribute,
getIntegerAttribute,getRealAttributeandgetStringAttribute).Youpassthenamesofthe
attributeanditsfieldasargumentstooneofthesefunctions.Youmustusethesefunctionin
connectionwiththetypedefinedfortheattributefieldinthe.s4hfile.Forexample,typeSTRING
requirestheuseofgetStringAttribute.
TosetanattributevalueyouusecallstosetAttributewiththeappropriatearguments(attribute
name,fieldnameandvalue).
ThekeypointtorememberinreadingandsettingattributesisthattheyareattachedtotheActivity
messages,andnottotheBusinessDocumentinstancesthataremovedacrosstheMappingFlow.
Asaconsequence,alloutputmessagessharethesameattributes.InacomplexMappingFlow,the
actualvalueoftheattributeistheresultofthelastcalltosetAttribute.
AttributesareusuallynottransferredautomaticallyacrossMappingFlows.Youexplicitlycallthe
appropriategetandsetfunctionstocopytheirvaluefrominputmessagestooutputmessages.
MorecomplexMappingFlowsmightrequiretoreadortochangeattributevaluesattheBusiness
Documentinstancelevel.AtypicalsituationofthisisaMappingFlowthatmanagesasinglemessage
withmultipleinstancesofaBusinessDocumentinside.
Inthediagramabove,theidentifierofeachinvoiceiscomputedbytheDMLBlocksoftheMapping
Flow.ThatidiscarriedbyanattributenamedinvoiceIdwhichistransferredtoindividualoutput
messages.TocreateaMappingFlowwithsuchabehavior,attributesmustbemanagedatdocument
instancelevel.
Theintegrationengineofferstwobuilt-infunctionstosettheattributesatdocumentinstancelevel.
ThesearesetDocumentAttributeandsetDocumentAttributeToOutput.Theformercannotbe
usedoutsideaMapandaddressestheoutputdocumentofthatrule.Thelatercanbeusedin
decisionpathsonlyandaddressesthedocumentcarriedbytheoutputwhosenameisspecifiedas
anargument.
Thefollowingareexamplesofthesignatureofbothfunctions:
setDocumentAttribute(attribute name,
attribute field name (optional),
value)
setDocumentAttributeToOutput(output name,
attribute name,
attribute field name (optional),
value)
Allnames(attribute,fieldandoutput)areexpectedtobeofclassS(string)whilevaluescanbeof
anyappropriateclassexceptV(raw-data).Forstructuredattributes,thefieldnameisrequired,but
canbeomittedforattributesofsimpletype.
Bothfunctionsfailwhentheclassofthevaluedoesnotmatchthetypeoftheattributefromits.sh4
file.
Context attributes
Inadditiontotheextradataattachedtomessagestransferredfromactivitytoactivity,the
integrationengineownsaglobaldictionaryofdata.Thecontentsofthisdictionarycanbeused
anywhereintheintegrationengineandispermanentlystored(restoredevenafterasystemcrash).
Entriesinthisdictionaryarecalledcontextattributes.WiththreespecificDMLbuilt-infunctions,you
caneitherinsertanewentryinthisdictionary,readorremoveanexistingentry.
l Toinsertanewentry,callthesetContextAttributefunctionandspecifythekey(astring)and
thevalue(anotherstring)youwanttolink.Youwillreceiveanexceptionifthekeyalreadyexists
inthedictionary.
l Toreadanentry,callthegetContextAttributefunction.Youspecifythekeyandyoualways
receiveastringvalue.Whennoentryforthespecifiedkeyexistsinthedictionary,thecall
evaluatestotheabsentsymbolicvalue.
l Toremoveanexistingentry,usetheremoveContextAttributefunctionwiththekeyasthe
uniqueargument.Anexceptionisraisedifthekeyisnotpresentinthedictionary.
Unliketomessageattributes,contextattributesareglobalandnotattachedtoanyotherdata.They
aretheprivilegedwaytostorepermanentinformationthatmightbeusedinmultipleintegrations
andbymultipleproc-engines.
Index classI34
classR34
classS34
classV34
$
date34
$38
integer34
A
rawdata34
absent35
real34
Activity10
string34
addition45
Concatenating53
assignment36
contextattributes152
B
customfunctions109
basicexpressions29
D
boolean34
date34
booleanexpressions71
decisionpath14
booleanoperators73
defaultcase77
BuildingtheFlow27
division45
built-infunctions50
DML15
BusinessDocument11
DMLBlocks
instances59
definition11-12
BusinessDocuments
DMLexpression13
creating18
E
C
endlessloops87
cardinality60
events130
case
endevent130
oftext55
errorevent130
classes
startevent130
boolean34
exceptions129
classB34
exponentiation46
classD34
expressions36
externalmultiplication53 instructions
F break87
Flow10-11 definition29
builda27 exit129
FoodBroker9,17 next87
determiningincomingID51 integer34
fillingheaders38 integrationengine9
generatingorderID57 integrationprocess10
fullyqualifiedname32 L
functiondeclaration114 lessthan72
functions lessthanandequalsto72
body114 libXIBcf.dll115
built-in50 libXIBcf.so115
formalparameters112 literals
functiondefinition110 date-and-time31
implementation114 numbers30
parameters110 strings31
realparameters112 M
G Map12
greaterthan72 MappingProject
greaterthanorequalsto72 sample16
H messageattributes148
handlesoncontainers116 systemattributes148
headers userdefined149
filling38 multiplepaths93
I multiplication45
implicitconversion35 multiplying53
implicitdynamiclink121 N
initializationexpression36 namingobjects32
inputs12
nodes59 outputs12
pathto59 P
null35 paths
numberclasses46 @specifier61
numbers30,45 @@specifier67
O \connector61
objects \\connector61
naming32 allnodes61
operators45 ambiguouspath62
-45 attributenodes61
*45 bracketspecifier64
**46 cardinalityerror63
/45 choicenodes61
:=36 definition60
+45 itemplaceholder65
<72 parentoperator..61
<=72 relationshipconnectors61
<>71 sequencenodes61
=71 specifyinginput62
>72 whereclauses65
>=72 priorityorder74
and73 promotions35
defined80 R
definition29 raisinganexception129
in72 rangeofvalues78
not74 rawdata34
or73 referenceinformation144
out72 reject129
undefined80 rejectMessage129
xor74 rel34
S this92
shareinformation37 thisindex99
statements thisisfirst99
assignment36 thisislast99
cardinalitystatement95 time
definition29 accuracyspecifier48
foreach97 evaluatedurations47
foreachdo98 performingshifts47
ifthenelse75 stickyendofmonthparadigm48
loop83 to78
loopon91 transactions
select103 commit133
switch77 concept131
times95 endtransaction131
timesdo95 instancetransaction131
tree100 rollback133
while86 starttransaction131
strings31,34,53 trimming54
changingtextcase55 truthtables73
selectingapart55 types15
trimmingandpadding54 V
subtraction45 ValidationRules15
symbolicvalues34,47 values
T specifying38
tableobject145 symbolic47
checkingkeymatches147 variables35
keycolumns145
rowvalidityperiod145
valuecolumns145
textcase55