0% found this document useful (0 votes)
191 views156 pages

MappingServices 3.0.1 GettingStarted DML AllOS en

axway

Uploaded by

Sunny Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
191 views156 pages

MappingServices 3.0.1 GettingStarted DML AllOS en

axway

Uploaded by

Sunny Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 156

GETTI NG STARTED GUI DE

Axway Mapping Services

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

2 Using basic expressions 29


Aboutexpressions 29
Usingliterals 30
Namingobjects 32
Handlingdata 33
Storingdatainvariables 35
Specifyingvaluesimplicitlyandexplicitly 37
FoodBrokerproject:Fillingheaders 38

3 Using numbers and operators 45


Usingbasicmathoperators 45
Usingoperatorsandnumberclasses 46
Symbolicvalues 47
Makingprecisionconsiderations 47
Timearithmetic 47
Advancedmath:acollectionofbuilt-infunctions 50
FoodBrokerproject:DeterminingtheincomingorderID 51

4 Working with strings 53


Concatenatingandmultiplying 53
Computingstringlength 54
Trimmingandpadding 54
Changingtextcase 55
Selectingpartsofastring 55

4Getting Started Guide Axway Mapping Services DML 3.0.1


Replacingparts 56
FoodBrokerproject:GeneratingtheorderID 57

5 Getting data from input: Paths to nodes 59


Beforeyouproceed 59
Elementarypaths 60
Ambiguouspaths 62
Pathcardinalities:Selectingoccurrences 63
Advancedselectionwithwhere 65
@@Specifier 66
FoodBrokerproject:Firststepsinfillingnodes 67

6 Making decisions with conditional statements 71


UsingBooleanexpressions 71
ConnectionswithBooleanoperators 73
Testingconditionswithif-then-else 75
Advancedtestingwithswitch 76
Testingfortheexistenceofanode 79
FoodBrokerproject:ExtrachargeforVISApayments 80

7 Repeating statements with loops 83


Repeatingafixednumberoftimes 83
Reachingacondition 86
Handlingirregularities:passandabort 87
FoodBrokerproject:Introductiontodataaggregation 89

8 Handling multiple occurrences 91


Goingthroughoccurrences 91
Generatingafixednumberofoccurrences 93
Generatingoccurrencesfromoccurrences 97
Questioningloopprogress 99
Copyingpartsofinputs:Thetreeinstruction 100
SelectingchildrenofaCHOICEparent 101
FoodBrokerproject:Collectingandcopyingparts 104

9 Extending DML with Custom Functions 109


Aboutfunctions 109
Usingafunction:functioncalls 110
Definingafunction 110
Declaringafunction 114
ImplementingCustomFunctionsinC 115
Gettinganoverview 115
ExchangesbetweencontainersandstandardCtypes 116
Containersandsymbolicvalues 119

Axway Mapping Services DML 3.0.1 Getting Started Guide5


Detectingerrors 120
Environmentconsiderations 120
WorkingwithSQLCustomFunctions 121
WorkingwithJavaCustomFunctions 122
FoodBrokerproject:Managingrates 124

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

6Getting Started Guide Axway Mapping Services DML 3.0.1


Preface
0
Purpose of this manual
ThisdocumentprovidesanintroductiontotheuseoftheDataManipulationLanguage(DML)
availableforuseintheAxwayMappingServicesp roduct.

Who should read this manual


ThisdocumentisintendedforAxwayusersinterestedintheAxwayproprietaryDML.Itisaddressed
toawideaudience,frombeginnertoadvanceduser.

Assumed knowledge
Inthisguide,weassumethatyouarefamiliarwiththeB2BorA2Aexchangesandthatyouhave
someknowledgeofAxway5Suite,AxwayIntegratorandAxwayMappingServices.Nospecific
programmingskillsarerequired,butweassumethatyouarefamiliarwithdatamappingconcepts
andtheintegrationengineobjectssuchasBusinessDocumentsorDMLBlocks.

Related documentation
Axway5Suite,AxwayIntegratorandAxwayMappingServicesareeachaccompaniedbyacomplete
setofdocumentation,coveringallaspectsofusingthecomponent.

AllAxwaydocumentationisavailablefromtheSupportwebsite:https://support.axway.com.

Axway Mapping Services DML 3.0.1 Getting Started Guide7


0 Preface

8Getting Started Guide Axway Mapping Services DML 3.0.1


Introducing DML
1
ThisguideintroducesyoutoDMLbyleadingyouthroughanexampleproject.Youwillget
informationabouthowtouseDMLinanintegrationengineandanintroductiontotheFoodBroker
sampleproject.

FoodBrokerisacompleteprojectofdatamappingforanimaginarybusinessfirm.Thisguidehelps
youtobuildthisprojectstepbystep.Thelastsectionofeachchapterinthisguideisdevotedto
deepeningandenhancingthisFoodBrokerproject.

ExampleFoodBrokerprojectsaredeliveredwithintheAxwayMappingServicesinthedirectory
<MappingServices>\Exercises\Getting started with DML\.Youcanusetheseprojectsasa
basisforyourtestsandtobecomeacquaintedwiththeDML.

Afterhavingcompletedthefirstc hapter,youshouldhaveabetterunderstandingofDML,you
shouldknowwhatstepstofollow,andhowtoconvertyourdatamappingneedsintoaworking
pieceofDMLcode.

Mapping data in an integration engine


ThegraphicillustrateshowtheAxwayproductsenablecompaniestointegrateacrossenterprise
systems,B2Bcommunities,andthecloudtoenablemobileapplicationsandprovideend-to-end
visibility.ForAxway,governingtheflowofdatameansmanagingdataexchangesbetween
participantsinthecontextofagivenbusinessinteraction.Itisthroughthiscontextthatenterprises
canprioritizeprocessingandactonthedataappropriately.

Anintegrationengineisasystemthathelpsyouprocessyourbusinessdatawhereveritcomesfrom
andwhateveritsformat,andtosenditontorecipientapplicationswiththedatastructurethey
expect,usingthedesiredtransportmode.Axwayprovidesthefollowingintegrationengines:B2Bi
andAxwayIntegrator.

Axway Mapping Services DML 3.0.1 Getting Started Guide9


1 Introducing DML

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.

10Getting Started Guide Axway Mapping Services DML 3.0.1


Understanding Mapping Flows

Understanding Mapping Flows


Basically,MappingFlowsarenetworksofDMLBlocks.DMLBlocksaresmallprocessingenginesthat
handledata.ThisnetworkofDMLBlocksdefinesthepathsfollowedbythevariousformsofdata
thatareprocessed.

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:

Axway Mapping Services DML 3.0.1 Getting Started Guide11


1 Introducing DML

ThemainideabehindMappingFlowsistospreadcomplexmappingsacrossseveralelementary
processingunits,combiningsimpletaskstomakemorecomplexones.

Understanding DML Blocks


MainBlocksaresmallprocessingenginesthatgeneratenewdatabyusing(ornotusing)incoming
data.IncomingdataissuppliedtoMainBlocksthroughtheirinputsandtheresultinggenerateddata
istransferredoutsideMainBlocksthroughtheiroutputs.Youcandefineasmanyinputsandoutputs
asneeded,eachwithadifferentname.

BeforeprocessingaMainBlock,theintegrationengineserverfeedsallinputswiththeappropriate
data.Thekeyconcepthereisthatinputdataismadeavailablebyaprocessthatisexteriortothe
MainBlock.ThismeansthatwhendefiningtheinternalprocessesoftheMainBlockyoudonotneed
toissueinstructionsfordatacollectionbecausethisisalreadydone.Youonlyneedtodefinewhich
partsofthedatahavetobetopicked-upforthegenerationofoutput.

MainBlocksaresoftwareprogramsthatmapdata,therefore,youhavetoprovideinstructionstotell
themhowtoperformthisaction.Thiscanbedoneinthreeways,dependingonthetypeoftheMain
Block:

typeMain Block Instructions are supplied using

WSBlock WebServiceschannel

DBBlock DBchannel

SAPBlock SAPchannel

DMLBlock DMLexpressions

BecausethisguideisdedicatedtoDML,youareconcernedherewithDMLBlocksonly.

DMLBlockscangeneratedatatomultipleoutputs.Eachoutputcarriesdatausingacertainformat
definedintheBusinessDocumentattachedtothisoutput.InstructionsarestructuredinDMLBlocks
aroundtheformatoftheoutput.ForeachoutputBusinessDocument,youdefineasetofruleson
howtobuildthisoutputBusinessDocument.SuchasetofrulesiscalledaMap .

12Getting Started Guide Axway Mapping Services DML 3.0.1


Understanding DML Blocks

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide13


1 Introducing DML

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.

14Getting Started Guide Axway Mapping Services DML 3.0.1


Approving input data with Validation Rules

Approving input data with Validation


Rules
DMLisalsousedtodefinetherulesthatcheckwhetherinputdataiseligibletobeprocessedbya
MappingFlow.TheserulesarecalledValidationRulesandareattachedtoBusinessDocuments.The
followinggraphicshowsaValidationRuleasitmightbedisplayedinAxwayMappingServices:

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

Axway Mapping Services DML 3.0.1 Getting Started Guide15


1 Introducing DML

memoryallocation.Althoughanexperiencedprogrammerwillrecognizesomeofthestandard
structures,techniquesandvocabularyofprogramminglanguages,DMLexpressionsaremuchmore
similartomathematicalformulasthanrealCorJavacode.

FoodBroker project: Doing the first steps


FoodBrokerisacompletesampleMappingProjectthatredisplaysattheendofeachchapterofthis
guide.Fromchaptertochapter,youwillseetheprojectdevelopedusingtheknowledgeyouacquire
fromthematerials.

TointroduceFoodBroker,imaginethatyouarecurrentlyworkingfortheInstantTakeOutcompany
whosebusinessistodeliverpreparedmealstocustomersattheirhome.TheInstantTakeOut
companyinvitescustomerstoconnecttotheirwebsite,selectarestaurant,andplaceanorderfor
homedeliveryofmeals.

16Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Doing the first steps

Thefollowinggraphicillustratesanexamplesoftwaretopologyforthisscenario:

Tomakesuchabusinesswork,youneedtoexchangedatabetweenseveralsoftwarecomponents.
Thesecomponentsmightinvolverecentlyacquiredhardwareandsoftwareaswellaselementsthat
youacquiredandinstalledseveralyearsago.

Inthissituation,processingofincomingordersisneededtoobtaindifferenttypesofdataforboth
ordersforrestaurantsanddeliveriesandbilling applicationinputs.Thisisbecausetheseapplications
acceptdataonlywhenformattedinaspecificway.

InthisFoodBrokersolution,orderprocessingisperformedbyanintegrationengineusingaDML
BlockthatconvertseachXMLdocumentfromthesaleswebserverintotwodifferentoutputXML
documents:the order for restaurantanddelivery and billing data.

Axway Mapping Services DML 3.0.1 Getting Started Guide17


1 Introducing DML

Creating a Business Document for the


customer request
ThefollowingisanexampleoftheXMLinputfromthewebserver:

<?xml version="1.0" encoding="ISO-8859-1"?>


<order>
<currency>USD</currency>
<payment>VISA</payment>
<date>2007-03-10</date>
<customer>
<name>James T. Johanson</name>
<id>C-070310-150</id>
<address>
<line>White House</line>
<line>1600 Pennsylvania Avenue NW</line>
<city>Washington</city>
<zip>20500</zip>
<state>DC</state>
<phone>202-456-1111</phone>
<fax>202-456-2461</fax>
</address>
</customer>
<supplier>
<name>Bombay Club Restaurant</name>
<id>S-150110</id>
<address>
<line>815 Connecticut Ave NW</line>
<city>Washington</city>
<zip>20006</zip>
<state>DC</state>
<fax>202-659-5012</fax>
</address>
</supplier>
<line>
<item>calamari peri peri</item>
<qty>2</qty>
<price>7.5</price>
</line>
<line>
<item>masala crab cake</item>
<qty>2</qty>
<price>12</price>
</line>
<line>

18Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Doing the first steps

<item>tandoori mixed grill</item>


<qty>1</qty>
<price>22</price>
</line>
<line>
<item>lamb biryani</item>
<qty>1</qty>
<price>14.95</price>
</line>
<line>
<item>naan</item>
<qty>5</qty>
<price>2.5</price>
</line>
<line>
<item>Chardonnay Shale Ridge</item>
<qty>1</qty>
<price>30</price>
</line>
</order>

Axway Mapping Services DML 3.0.1 Getting Started Guide19


1 Introducing DML

First,youneedaBusinessDocumentthatmatchesthisXMLinputfile.TocreatetheBusiness
Documentproceedasfollows:

1. InAxwayMappingServices,intheleft(Project Explorer)frame,callthecontextmenuofthe
subdirectoryBusiness Documentinyourproject.

20Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Doing the first steps

2. SelectNew -> Business DocumentfortheWizardtocreateanewBusinessDocument.

3. ClickNext andgivethenameofthenewBusinessDocument

Namefield:EnteranameforthenewBusinessDocument.ThisexampleusesBD_
orderFromWebasthename.ClickonFinish,thedocumentwillbecreatedandtheEditor
viewisopened.

Axway Mapping Services DML 3.0.1 Getting Started Guide21


1 Introducing DML

4. IntheEditorview,defineacompletesetofBusinessDocumentnodestomatchthestructure
oftheincomingXMLdocument,asinthefollowinggraphic:

5. Checkandsavetheobject.

Creating a Business Document for the


partner
Whenanorderisreceivedfromthecustomer,itistransmittedbyfaxtotheappropriaterestaurant
thatpreparesthedishes.Inthisexamplecompany,therestaurantorderssoftwareisanapplication
thatdrivesafaxmachine.Thisapplicationfillsincomputer-basedformswiththedataitreceives,
andthensubmitstheresultingformtoafaxmachinefortransmissionusingthephoneline.

Asaresult,theXMLdocumentacceptedbythisapplicationasaninputrequiresthreekindof
information:

l Afaxnumber,whichisnotpartofthefaxdocumentbecauseitisdirectlytransmittedtothefax
driver
l Senderandrecipientinformation,whichisusedtofillinthecaptionofthefaxdocument
l Rawtext,whichincludesthedetailsoftheorderandthatconstitutesthebodyofthefinalfax
document

22Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Doing the first steps

ThefollowingXMLfileisanexampleofinputfortherestaurantorderssoftwarethatmustbe
extractedfromtheXMLinputofthesaleswebserver:

<?xml version="1.0" encoding="ISO-8859-1"?>


<order>
<fax>202-659-5012</fax>
<caption>
<sender>
<name>Instant TakeOut</name>
<phone>202-978-0502</phone>
<fax>202-978-0502</fax>
</sender>
<recipient>
<name>Bombay Club Restaurant</name>
<phone>202-659-5052</phone>
<fax>202-659-5012</fax>
</recipient>
<orderid>20070310450</orderid>
</caption>
<body>
2 x calamari peri peri
2 x masala crab cake
1 x tandoori mixed grill
1 x lamb biryani
5 x naan
1 x Chardonnay Shale Ridge
</body>
</order>

ThesenderisyourInstantTakeOutcompanyandtherecipientistheappropriaterestaurant.The
wholeorderisincludedinthetextbody,withoutprices,butincludingquantities.Thisbodysection
isintheformofrawtext,witheachorderitemonseparatelines.

Axway Mapping Services DML 3.0.1 Getting Started Guide23


1 Introducing DML

RepeattheprocedureforcreatingaBusinessDocument,onlythistimenameitBD_
orderToPartner.DefinethestructureoftheBusinessDocumentasshowninfollowinggraphic:

Creating a Business Document for billing


and delivery
ThesamplecompanysdeliveryandbillingdataisprocessedbyanapplicationthatalsoacceptsXML
filesasinput.Thisapplicationperformstwotasks:

l Composingandprintingtheinvoicesthatarealsousedbytheemployeesofthecompanyas
deliverynotes
l Appendingtheinvoiceinformationtotheaccountingfilesofthecompany
Theinputdocumentforthissoftwareisverysimilartotheorderthatcamefromthewebserver,
exceptthatsomeextraamountsarecomputed:

l Theorderprocessinganddeliveryfees,thatthecustomerischargedwith,thisis5%oftheorder
total
l Thefeespaidbacktothepartnerrestaurant:thisiscomputedfromthepreviousfeesusingarate
thatisrelatedtothepartner
l Thegrandtotaloftheinvoicethatincludesextracustomercharges

24Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Doing the first steps

PartnerfeescomefromanotherXMLdocumentinwhichpartnernamesarelinkedwiththerate:

<?xml version="1.0" encoding="ISO-8859-1"?>


<root>
<partner>
<name>Bombay Club Restaurant</name>
<rate>0.12</rate>
</partner>
<partner>
<name>Old Ebbitt Grill</name>
<rate>0.45</rate>
</partner>
<partner>
<name>Jaleo</name>
<rate>0.32</rate>
</partner>
</root>

Again,repeattheprocedureforcreatinganXMLBusinessDocument,thistimenameitBD_
billingDeliverytomatchthestructureofthisoutputXMLdocumentasshowninthefollowing
graphic:

ThisBusinessDocumentisverysimilartotheBD_orderFromWebBusinessDocument.The
differencesareinthenodeshighlightedinthepreviousgraphic:orderid,amount,charges,
partner_fees,andtotal.EachofthesenodesholdsvaluesthatyourDMLBlockcomputesfrom
thenodesoftheBD_orderFromWebBusinessDocument.

Axway Mapping Services DML 3.0.1 Getting Started Guide25


1 Introducing DML

Creating a Business Document for


partner rates
CreateafourthBusinessDocumenttoholdbillingrateinformationforthepartners.Repeatthe
procedureforcreatinganXMLBusinessDocument,butthistimenameitBD_partnerRates.Define
thestructureoftheBusinessDocumentasshowninfollowinggraphic:

26Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Doing the first steps

Building the Mapping Flow


BuildaMappingFlowthatprocessesthecontentoftheBD_orderFromWebBusinessDocumentto
generateBD_orderToPartnerandBD_billingDeliveryBusinessDocumentsandsendthemon
totwodifferentoutputs.TheMappingFlowisbuiltaroundaDMLBlockthatperformsthistask,
whichisnamedMB_extractorinthefollowinggraphic:

InthisMappingFlow,theinputXMLdocumentistransmittedfromInput1totheMB1_extractor
DMLBlock.MB1_extractorgeneratesafirstXMLdocumentonitspartneroutputandanotherone
onitsbillingoutput.Thesedocumentsarethentransmittedtotheirrespectiveapplications
throughtheMappingFlowoutputspartner_faxandbilling_delivery.

Amorecomplexsolutionisrequiredtoprovidepartnerrates.YourcompanypossessesanXMLfile
containingtherates.TousethecontentofthisfileyoumustaddtwomoreDMLBlockstothe
MappingFlow:MB_tableLoaderandMB_tableBuilder.

Axway Mapping Services DML 3.0.1 Getting Started Guide27


1 Introducing DML

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.

28Getting Started Guide Axway Mapping Services DML 3.0.1


Using basic expressions
2
Asseeninthepreviouschapter,checkingormappingdatausingDMLconsistsofwritingspecial
piecesoftext.Inthischapter,youseethatthosepiecesarecalledexpressionsandyoulearnhow
theyarecomposed.

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:

(1992 + 89) * 78.9

Thisexpressiontellstheintegrationenginetoadd89to1992andthentomultiplytheresultsby
78.9.Themeaningisabsolutelythesameasinconventionalmathexpressions.Noticetheuseof
reservedcharacters(,),+and*asarithmeticalsymbolsforpriority,addition,andmultiplication.

Inthisexample,theresultvaluethatisgeneratedis:164190.9.MostDMLexpressionsgeneratea
valuethatisusedbytheintegrationengineaseithertheresultofdatacheck,ortofillnodesof
outputdata.

ThisiswhyexpressionsareboundtoBusinessDocumentsorBusinessDocumentnodes.Thevalue
generatedbyaValidationRuleofaBusinessDocumentstateswhethertheinputdocumenthasbeen
successfullycheckedornot.ValuesgeneratedbyMapsareusedbytheintegrationengineserverto
fillthecorrespondingnodesintheoutputBusinessDocument.

Axway Mapping Services DML 3.0.1 Getting Started Guide29


2 Using basic expressions

Instructionsandoperatorsactonobjectsasshowninthenumbersinthepreviousexample.Those
numbersareamongthemostprimitiveobjectyoucanseeinexpressions:literals.Morecomplex
objectsdoexistintheintegrationengine;thesearereferredtousingtheirnames.

ThefollowingisthelistofDMLreservedkeywordsandcharacters.

( ) { } [ ]

; , + - / &

:= = <> \ \\ ..

* : $ in out <

<= >= > " ' @

@@ % ! {# #} **

and attribute absent break case child

default defined do else exit each

for false if item into loop

next not null on or parse

select switch tree this then to

times terminal true undefined while where

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.

30Getting Started Guide Axway Mapping Services DML 3.0.1


Using literals

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:

"the quick brown fox jumps over the lazy dog"


" A"

Anirritatingcharacteristicofthequotesisthattheyarenotspecialcharactersthatappearonlyin
computerprograms.TheyareapartofanynormalEnglishtexttoindicateemphasisorthat
someonehasspoken.Thequotesinaliteralstringhaveadifferentmeaningthanthequotesthat
surroundtheliteral.

Sincethereisonlyonekeyonyourkeyboardtomakeaquote,youcanuseatechniquethatiscalled
escaping .Inmostcomputerlanguages,atleastonecharacter,calledanescapecharacter,is
designatedtohavethepowertoremovethespecialsignificancefromotherspecialcharacters,such
asquotes.InDML,thischaracteristhebackslash(\).

Topreventtheintegrationengineserverfromthinkingthatithasprematurelyreachedtheendof
yourstring,youneedtoescapethequotesinyourstringsasshowninthefollowingexample:

"He said \"using quotes in strings is irritating\""

statestherealstring:He said using quotes in strings is irritating

InDMLyoucanusethefollowingescapesinstringliterals:

\" fordoublequote(")

\\ forrealbackslash(\)

\t fortabulationcharacter

\r forcarriage-returncharacter(ASCII0x0D)

\n forline-feedcharacter(ASCII0x0A),notthenewline.

Theremainingtypeofliteralyoucanuseinexpressionsisadate-and-timeliteral,usuallynamed
dateliterals.Thisliteralisusedtorefertoaspecialmomentintime;eitherjustadayintheyear,ora
precisemomentofthatday.

Axway Mapping Services DML 3.0.1 Getting Started Guide31


2 Using basic expressions

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.

32Getting Started Guide Axway Mapping Services DML 3.0.1


Handling data

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide33


2 Using basic expressions

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.

34Getting Started Guide Axway Mapping Services DML 3.0.1


Storing data in variables

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".

Storing data in variables


Whencombiningandmappingdata,youmightwanttousethesameintermediateresultsmorethan
onetime.Yourquestionthenshouldbe:mustIcomputetheintermediatevaluerepeatedlyeach
timeIneedit?TheDMLlanguageoffersyouaclipboardfacilitythroughobjectscalledvariables.

Axway Mapping Services DML 3.0.1 Getting Started Guide35


2 Using basic expressions

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

36Getting Started Guide Axway Mapping Services DML 3.0.1


Specifying values implicitly and explicitly

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.

Specifying values implicitly and


explicitly
Expressionsarecomposedofstatementsthatincludeinstructions,operators,andliterals.Youcan
usevariablesandnamesofobjects.Togethertheseelementsarecombinedinthecomputationofa
finalvalue.Incalculatingtheresultingvalueofthefollowingexpression,youcanspecifythevalue
ofanexpressinDMLeitherexplicitlyorimplicitly:

%pi := 3.14; %area := %pi * %radius * %radius; %height * %area

Axway Mapping Services DML 3.0.1 Getting Started Guide37


2 Using basic expressions

Thisexampleusestheimplicitmethod:itsvalueis%height * %area.Thevalueofanexpression
isimplicitlysetbyitslaststatement.Thisiscorrectonlywhenthelaststatementgeneratesavalue:
multiplicationdoes,assignmentdoesnot.

Tospecifyexplicitly,usethereservedcharacter$thatreferstotheexpressionvalue.Writing$ := 4
inanexpressionmeansitsactualvalueis4.

FoodBroker project: Filling headers


IntheprevioussectionsofthischapteryouhaveseenDMLexpressionsthatyoucanuseinthe
integrationengine.NowyoucanputyourknowledgeintopracticeintheFoodBrokerproject.

ThefollowingisasimpleexercisetodefinethebasicMappingFlowwiththeMB_extractorDML
BlockandtheXML-header-fillingsectionofaMap.

Intheproject,theMB_extractorDMLBlockisusedtogeneratetwooutputs.Youneedtodefine
andactivatetwoseparateMapstofillthesetwodifferentdocuments.

38Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Filling headers

1. OpenthecontextmenuatthedirectoryMapsinyourprojectandselectNew -> Map.

Axway Mapping Services DML 3.0.1 Getting Started Guide39


2 Using basic expressions

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:

40Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Filling headers

4. Intheexpressionfieldfor:
XmlVersionnode,enter"1.0"
XmlEncodingnode,enter"ISO-8859-1"
Thisisthesimplestuseofexpressions:Youenterthestringliteralsthatyouwanttoinputtothe
correspondingnode.
5. Usingthesamemethod,defineasecondMapthatgeneratesdataforthebillingsystemand
routestheinputdocumenttothebillingoutputoftheDMLBlock.
Thistime,includeavariation:Placethevaluesfortheversionandencodingnodesin
variables.
DefinetherequiredvariablesbyusingthecontextmenuontheExtended Objectsdirectory.

Axway Mapping Services DML 3.0.1 Getting Started Guide41


2 Using basic expressions

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.

42Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Filling headers

Creating the Mapping Flow that process the data through the developed
Business Documents and Maps
1. CreateanewMappingFlowandnameitordertoPartner:

Axway Mapping Services DML 3.0.1 Getting Started Guide43


2 Using basic expressions

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.

44Getting Started Guide Axway Mapping Services DML 3.0.1


Using numbers and
operators 3
TheB2Btypeexchangesthatyoumighthandleintheintegrationengineveryoftenrelateto
orderingandbilling.AnimportantcapacityofDMLforthistypeoftransactionisitsabilityto
manipulatenumbers.

Inthischapter,youreturntotheuseofnumbersandsomeofthewaysinwhichDMLworkswith
them,includingbasicarithmeticandmoreadvancedfunctions.Thecommonpitfallsofusing
numbersintheintegrationengineenvironmentareincluded.

Whenyouhavefinishedthischapter,youwillbefamiliarwiththebasiccategoriesofnumbersthat
DMLuses,andwiththeoperatorsandbuilt-infunctionsforusingthem.

Using basic math operators


Thefourbasicwaysincombiningnumbersareadding,subtracting,dividingandmultiplying.By
usingonlythesefourbasicoperations,youcancreateanytypeofcomplicatedmathematical
formula.

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)

Axway Mapping Services DML 3.0.1 Getting Started Guide45


3 Using numbers and operators

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.

Using operators and number classes


ThebasicmathoperatorscanbeusedtocombineanynumbersofeitherclassIorclassR.Map
expressionssimilartothefollowingarelegalandperformtheexpectedcalculations:

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.

46Getting Started Guide Axway Mapping Services DML 3.0.1


Symbolic values

Symbolic values
Similartoanyotherdata,numbersintheintegrationenginecanhaveoneofthetwosymbolic
valuesnullorabsent.

Thesevaluesabsorbothervalueswhenusingbasicmathoperators.Thismeansthatwhateverthe
operatoris(+,-,*or/),theresultingvaluewillbenullasshowninthefollowingexamples:

56.05 + absent null


45 * null
absent absent null
null / absent null

Making precision considerations


Becauseoftheunderlyingtechniquesusedtoperformmathonfloating-pointnumbers,calculation
errorsmightoccurinyourexpressionresults.Thenumbersyoumanipulatehavealimitedprecision,
youcannotcombinehugeandtinynumbers.Computingthevalue510 200+510 -200isbeyond
thecapacityoftheintegrationengineserver.

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 ,

Axway Mapping Services DML 3.0.1 Getting Started Guide47


3 Using numbers and operators

2001.BothoftheseexpressionsevaluatetoJanuary 1 st, 2001.Formally,addingorsubtracting


anintegertoorfromadateshiftsthatdateeitherinthefuture(addition)orinthepast(subtraction)
ofthenumberofdaysstatedbytherightoperand.

Timeshiftsarecomputedusingcompletedaysandalldateandtimecomplexityishandled.For
example:

'2007-03-01 15:17'-1evaluatesto'2007-02-28 15:17'

while

'2008-03-01 15:17'-1evaluatesto'2008-02-29 15:17'

Thelastexpressioncombinestwodatestocomputethenumberofcompletedayselapsedbetween
thetwooperands,thatexpressionevaluatesto1:only47hoursand59minuteselapsedbetween
thetwodates,thatisenoughforonedaybutnotfortwo.

Shiftingorcomputingdurationusingdaysisusuallyenough.Butundercertaincircumstances,one
mightappreciatetodealwithseconds,minutes,hours,monthsoreitheryears.Thiscanbe
accomplishedwiththe+andoperatorsassociatedwithoneaccuracyspecifier.Fiveaccuracy
specifiersareavailableinDML,theseare:

Specifier Accuracy used

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.

48Getting Started Guide Axway Mapping Services DML 3.0.1


Time arithmetic

Inaddition,monthshiftsfromdatesafterthe28 th ofamonthnevercrossmonthends.Shouldthe
resultingdatenotavaliddateintheGregoriancalendar(suchasJune31 st),itisadjustedtothelast
dayofthemonth.Youcouldsaythatendsofmonthsarestickywhencomputingtimeshifts.

Thefollowingaresomeexamples:

'2003-01-13' +M 1 '2003-02-13''2008-01-31' +M 3 '2008-04-30'


'2008-01-31' +M 1 '2008-02-29''2003-05-31' -M 3 '2008-02-29'
'2008-01-31' +M 2 '2008-03-31''2006-04-30' -M 1 '2006-03-30'

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:

'2008-09-18 08:55' s '2008-09-17 08:54'86460


'2008-09-18 08:55' h '2008-09-17 08:54'24
'2008-09-18 08:54' M '2008-09-17 08:54'0
'2008-09-18 08:54' Y '2008-09-17 08:54'0

Theobtainedvaluecanbethenumberofseconds,minutes,hours,ordayscompletelyelapsed
betweenthetwodates.Fordurationsinmonthsandyears,thevalueobtainedisthebiggest
possibleshiftoftherightoperandthatgeneratesadateanteriortotheleftoperand.Thismethod
ensuresconsistencywiththewaymonthsshiftsareprocessed.

Axway Mapping Services DML 3.0.1 Getting Started Guide49


3 Using numbers and operators

Advanced math: a collection of built-in


functions
Bycombiningmathematicaloperators,youcancreatepracticallyanytypeofmathematicalformula.
Becausesomemathematicalformulasarecumbersome,theintegrationengineprovidessomebuilt-
infunctionsforperformingmoreadvancedcalculations.Thefollowingtabledisplayssomeofthose
built-ins:

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.

50Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Determining the incoming order ID

FoodBroker project: Determining the


incoming order ID
Tomakethecompleteprocessingchainworkproperly,thecompanystaffdecidedtoincludean
identifierforeachordersubmittedbycustomers.ThisorderIDmustbecomputedbytheDMLBlock
andtheresultinsertedineachoutputwhetheritbepartnerorbilling.

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:

Axway Mapping Services DML 3.0.1 Getting Started Guide51


3 Using numbers and operators

EntertheaboveexpressionintheMR_webToBillingMapyoudefinedpreviously.Youassociate
theexpressionwiththeorderidnodeasillustratedinthefollowinggraphic:

52Getting Started Guide Axway Mapping Services DML 3.0.1


Working with strings
4
Inthepreviouschaptersofthisguideyoulearnedabouttheuseofstrings,theS(string)class,its
purpose,andhowtoincludestringliteralsinyourexpressions.

Inthischapter,youwilllearnhowtocomputecomplexstringsfromseparateparts.Aquicktourof
theusefulthingsyoucandowithbuilt-instringfunctions,suchassplitting,padding,extracting
andsoon,isincluded.

Thischapterisintendedasanoverviewofwhatyoucandowithstrings.Onlythemainstring
manipulatingfunctionsarepresentedhere.Foradditionalinformationonstringmanipulationwith
DMLrefertotheDMLUserGuideandDMLReferenceGuide.

Concatenating and multiplying


Astringisthecomputerconceptfortexttypedata.Aswithnumbers,youcancombineandmaptext
inDMLexpressions.Thiskindofoperationisaccomplishedmainlyusingspecificfunctionsrather
thanrelyinguponoperators.

Themostbasicstringoperationiscalledconcatenation.Concatenationisforstringswhatadditionis
fornumbers.Whenyouwritesomethingsimilartothefollowing,youinstructtheintegrationengine
tobuildanewclassSvaluebymergingthethreestringliteralsleading,middleandtailing:

"leading" + "middle" + "tailing"

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide53


4 Working with strings

Computing string length


Acomputerlanguagethatpermittedonlyconcatenationandstorageofstringswouldbevery
limited.Theintegrationenginealsoincludesasetofbuilt-infunctionsthatprovideawiderangeof
stringmanipulation.

Oneofthesefunctionsisthelengthfunctionthatcomputesthenumberofcharactersinagiven
string.Forexample:

length("Greeting from our moon base alpha !")

Inthisexample,thelengthofthestringis35characters,includingspacesandthefinalexclamation
point.Thefunctionreturnsawholenumber(classIvalue)andcountsallthecharacters,including
leadingandtailingspaces.

Considerasecondexample:

length(" Redde Csari qu sunt Csaris ")

Thisexpressionalsoreturnstheresult35.Leadingandtrailingspacesarecounted.Thecharacter
countsasasinglecharacterevenifitseemstobecomposedofanaandane.

Whenusingthelengthfunction,onlysinglecharactersarecounted,howeveryouenterthem(
countsforone,evenifyouuseeand^onyourkeyboardtoenterit),thenumberofglyphstheyre
composedof,orthewaytheyaretechnicallyencoded(aisencodedonfourbyteswhenUCS32is
used,butcountsonlyforonecharacter).

Trimming and padding


Youmightwanttoreducethestringtoitssignificantpartbyeliminatingspacesbefore(leading
spaces)orafter(trailingspaces)anyvisiblecharacter.

SpecialfunctionsareincludedinDMLtoaccomplishsuchtasks.Theseare:trimString,
trimStringLeft andtrimStringRight.Thesethreefunctionscreatenewstringsratherthan
changingthecontentsofthesuppliedones.Thefollowingareexamplesofvaluesreturnedbythese
threefunctions(greycolorisusedtodisplayspaces):

trimString(" significant part ") returns significant part


trimStringLeft (" significant part ") returns significant part
trimStringRight(" significant part ") returns significant part

Asyoucansee,leadingspacesareremovedbytrimmingandtrimStringLeftwherethetrailing
spacesareremovedbybothtrimStringandtrimStringRight.Spacesincludedwithinthetextare
notremoved.

54Getting Started Guide Axway Mapping Services DML 3.0.1


Changing text case

Thetrimfunctionsoperateonlyonstrings.Theyarenotlimitedinremovingspaces.Youcanuse
theiroptionalsecondargumenttoremoveanythingthatisundesirableinyourstrings:

trimString("0003.141592653500", "0") returns 3.1415926535


trimStringLeft("--a word", "-") returns a word
trimStringRight("the end;;;", ";") returns the end

Sometimes,youmightwanttoinsertspacestomakeyourstringconformtoacertainformat.Thisis
quitecommonwhendealingwithdocumentswhereinformationiscolumnar.Unsimilartotrimming,
onlytwofunctionsdopadding:

padStringLeft("original", 3) returns original


padStringRight("original", 3) returns original

Intheseexamples,threespacesareeitherinsertedatthebeginningorappendedattheendofthe
originalstringtomakeanewone.Inbothcases,thefinallengthincreasesfromeighttoeleven.

Changing text case


Whendealingwithromantext,allstringsconsistoflettersthatcandisplayinthefollowingways:

l inalllowercase

l INALLUPPERCASE(WHICHCANBECONVEYEDASSHOUTING)
l asamixofUPPERCASEandlowercaseletters,toemphasize
Toconverteverycharacterinastringtolowercase,usethefunctiontoLower,whereasfor
uppercaseconversion,usetoUpper.Similartotrimmingandpaddingfunctions,thesefunctions
generatenewstringswithcharacterschangedratherthanmodifytheoriginalones.

ThesefunctionsoperateasexpectedonlyonstringsencodedusingASCII-lineagecharactersets:
ISO646,ISO8851andallUnicodeUTFs.

Selecting parts of a string


Atthebeginningofthischapter,youlearnedaboutconcatenation:howtocombinestringstomake
biggerones.Youmightwanttoperformtheoppositeoperation:splittinglongstringsinto
elementarycomponents.Forexample,youmighthaveastringconsistingofthecompletenameofa
person,ofwhichyouwanttoconserveonlythelastname.

Axway Mapping Services DML 3.0.1 Getting Started Guide55


4 Working with strings

Youcanusethefollowingfunctionstoextractpartsofaspecifiedstring:

l getStringLeft(string, count)
Thisgeneratesanewstringvaluethatincludesonlythefirstcountcharactersofstring.
l getStringRight(string, count)
Thiscreatesanewstringvaluethatcontainsonlythecountendingcharactersofstring.
l getSubString(string, start-index, count)
Thisextractsthepartofthestringstringthatstartsatstart-indexth characterandiscountlong.
Herearesomeexamples:

getStringLeft("BOND, James Bond", 4) returns BOND


getStringRight("BOND, James Bond", 4) returns Bond
getSubString("2007-05-29", 6, 2) returns 05

Whenspecifyingcountorstart-index,alwaysusepositivewholenumbers(classI)toavoidreceiving
nullvaluesorerrors.

Specifyinginappropriateclassesforarguments(stringmustbeimplicitlyconvertibletoclassS,and
countandstart-indextoclassI)leadstoobfuscatederror:

DML-Function with compatible parameters does not exist.

Usingnegativevaluesforcountorstart-indexalwaysleadtonullvalue.Sodoesusingastart-index
thatisplacedaftertheendofthestring,forexamplegreaterthanthestringlength.Forstart-index,
rememberthatthefirstcharacterofthestringis1.

Replacing parts
Twofunctionsareavailablewhichenableyoutosearchforasubstringinastringandreplaceitby
anotherone.Theseare:replaceString andreplaceStringAll.Theformeroperatesonlyonthe
firstoccurrencewhilethelaterreplacesall.

Example

replaceString("Increase tax by ten per cent", "tax", "wages")


Generatesthestringvalue:Increase wages by ten per cent.

replaceStringAll("To be or not to be, thats the question", "be",


"work")
Returnsthestringvalue:To work or not to work, thats the question.

Inbothcases,theoriginalstringisreturnedverbatimifthesearchpatternhasnotbeenfound.

56Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Generating the order ID

FoodBroker project: Generating the


order ID
BoththeBD_orderToPartnerBusinessDocumentandtheBD_billingDeliveryBusiness
Documenthaveanorder_idnode.However,itisdefinedasastringinBD_orderToPartner.The
expressionthatcomputestheorderIDinthisdocumentisdifferentfromtheoneoftheprevious
chapter.

Usethecontentofthenowvariable,butthistimeitisprocessedasastringviaimplicitconversion
frominteger:

dayOfYear(%now) + getStringRight("00" + getHours(%now), 2)


+ getStringRight("00" + getMinutes(%now), 2)
+ getStringRight("00" + getSeconds(%now), 2)

TheresultsofthecalltogetHoursisconvertedtoastringbecauseitisconcatenatedtoanother
string.Tomatchtheresultsofthepreviouschapter,hours,minutes,andsecondsneedtoalwaysbe
twodigitslong.Toaccomplishthis,twoleadingzerosareaddedtoeachresultandthentheresult
stringiscuttoalengthoftwocharacters.

EntertheaboveexpressionintheExpressionfieldoftheorderidnodeintheMR_
webToPartnerMap.

InthisBusinessDocument,thesenderinformationisalwaysthesameandiswrittentothenodevia
stringliterals:

Axway Mapping Services DML 3.0.1 Getting Started Guide57


4 Working with strings

58Getting Started Guide Axway Mapping Services DML 3.0.1


Getting data from input:
Paths to nodes 5
Youhaveseenwaystowritedatatooutputnodesvialiteralsandvariables.Mostoftenyourgoalis
tomapdata,tocreateoutputstructureddatafrominputstructureddata.Inthischapteryouwill
learnhowtomanipulatedatafrominputBusinessDocumentsinDMLexpressions.

ThischapterdescribesoneofthemostcomplexaspectsofDML:pathstoBusinessDocuments
nodes.Youwillconsidereverythingfrombasicpathstocomplexpathsthatselectonlyspecificparts
ofaBusinessDocument.

Before you proceed


Beforeconsideringaboutpathstonodes,reviewsomeofthebasicconceptsofanintegration
engine.

Intheintegrationengine,theprocessingsequencethatdefinesanintegrationisdefinedinan
integrationprocess.Tomaketheindividualpiecesofdataofaninputmessageavailablefor
handling,theintegrationengineparsesthedatatoaBusinessDocumentinstance.Business
Documentsareformaldescriptionsofthewaythedataoftheinputmessageisstructured.

ABusinessDocumentdescribesthedatacarriedandmappedintheintegrationenginefroma
hierarchicalpointofview:BusinessDocumentsarecomposedofnodes.Eachnodeeitherholdsdata
orgroupsasubsetofnodes.NodesinBusinessDocumentsarenamed,butthesenamesdonothave
tobeuniqueinaBusinessDocument.

Axway Mapping Services DML 3.0.1 Getting Started Guide59


5 Getting data from input: Paths to nodes

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.

60Getting Started Guide Axway Mapping Services DML 3.0.1


Elementary paths

Apathiscomposedofthenamesoftheintermediatenodesthatyoumustpassthroughtoreach
yourgoal.Consideramailaddressincludedinaninvoice.Topositivelyindicatethecityname
containedintheaddress,youmightneedthefollowingpath:

invoice customer address city

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

Axway Mapping Services DML 3.0.1 Getting Started Guide61


5 Getting data from input: Paths to nodes

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.

62Getting Started Guide Axway Mapping Services DML 3.0.1


Path cardinalities: Selecting occurrences

Path cardinalities: Selecting occurrences


PathstonodesareusedinexpressionstoaddressdatathatresidesininputBusinessDocuments.
ReviewthefollowingifyouneedtodevelopaDMLBlockthatfillstheamountnodeinthefollowing
document:

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).

Axway Mapping Services DML 3.0.1 Getting Started Guide63


5 Getting data from input: Paths to nodes

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

64Getting Started Guide Axway Mapping Services DML 3.0.1


Advanced selection with where

Advanced selection with where


Thebracketoperatorisusefultoselectoneoccurrenceofamultipleoroptionalnode,providedthat
youknoworknowhowtocomputeitsexactindex.Insomesituations,thisisfartoolimited.You
knowwhatyouaresearchingbutnotexactlywhereitislocated.

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide65


5 Getting data from input: Paths to nodes

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.

66Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: First steps in filling nodes

Therefore,yourequireauniquepaththataddressesonlymy_funny_nodesthataredefined
havingvalues.Todothisyouusethe@@specifier.

Forexample,thefollowingpathaddressesonlythoseofmy_funny_nodethataredefinedhaving
values,whateverthecardinalityisandwhethervaluesaresettosomethingotherthanabsent:

\\@@my_funny_node

FoodBroker project: First steps in filling


nodes
Nowthatyouknowhowtocollectinputdataanduseittogeneratevalues,youcanfillsomemore
outputnodesoftheMB_extractorDMLBlock.

StartwiththeMapthatgeneratesthedocumentforthepartnerrestaurant.Filltherecipientpartwith
copiesofsupplierfieldsfromtheinput.Thefollowingtableliststhemappingofdatafrominputto
outputnode:

node in output filled with node from input

\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

Axway Mapping Services DML 3.0.1 Getting Started Guide67


5 Getting data from input: Paths to nodes

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:

%amount * 0.05 * rates:\partner\name[where item =


order:\Root\order\supplier\name]\..\rate

ThisexpressionselectstheratefrominputratesXMLdocumentusingthesuppliernamefoundin
theinputorderdocument.Then,thegrandtotalisquitesimple:

%amount * 1.05

Noticethatcomputingthefieldtotalisdoneonlyfromtheinput.InMaps,youcannotusethe
outputyouarecurrentlybuilding,eveniftotalisbasicallythesumofamountandcharges,you
cannotcomputeitthatway.

68Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: First steps in filling nodes

Thevaluesformappingtheremainingnodesof BD_billingDeliveryarecopieddirectlyfromthe
nodeswiththesamenamesinBD_orderFromWeb.Totelltheintegrationenginetoperformsuch
copies,youenterthepathstothesourcenodesaselementaryrulesintheMap.

Thisispossiblefornearlyeverynodeoftheoutput.Anupcomingchapterdescribeshowtohandle
thecaseofmultiplyoccurringnodes(nodeswithcardinality1..nor 0..n).

ThefollowinggraphicillustrateswhatyourMapshouldlooksimilartoatthispoint:

Axway Mapping Services DML 3.0.1 Getting Started Guide69


5 Getting data from input: Paths to nodes

70Getting Started Guide Axway Mapping Services DML 3.0.1


Making decisions with
conditional statements 6
ThepurposeofDMLexpressionsistomaketheintegrationenginebehaveinacertainway.Themost
primitivesetofexpressionsactexactlythesamewayeachtimetheyarerun,performingthesame
mappingofdata.

Suchprimitiveexpressionsmightworkfinewhendealingwithoutputsthatcloselyresembleinputs.
Ontheotherhandmanymappingsneedtoprocesscomplexandversatiledataandmodifytheir
behaviorbasedonthevariationsofdatatheyreceive,inwhichcaseprimitiveexpressionsareless
useful.

Insuchsituations,eachtimeyousupplytheintegrationenginewithdifferentdata,thesetof
expressionsyouenteredmightresultinadifferentoutput.Todeterminehowtogiveyour
expressionsthecapabilitytomakedecisionsandthereforebehavedifferently,youmustuse
conditionalstatements.

Using Boolean expressions


Manyofthedecisionsyoumake,involvechoicesbetweentwooptions.

Theintegrationengine,andcomputersingeneral,workinasimilarway.Whilepeoplecanask
questions,theintegrationenginecancheckBooleanexpressions.ABooleanexpressionisbasically
anythingthatrepresentsoneoftwovalues,suchastrue/falseor zero/non zero.Theclassof
suchexpressionsisclassB.

ThemostbasicquestiontheintegrationenginecananswerisAre these two values the same


or not?SuchBooleanexpressionarebasedontwooperators,=and<>,asshowninthe
followingexamples:

%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.

Axway Mapping Services DML 3.0.1 Getting Started Guide71


6 Making decisions with conditional statements

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:

%revision in ( "1.0", "1.1", "1.6", "2.0" )


\customer[1]\name in ( "John Doe", "Jane Smith" )
\invoice\date out ( \invoice\delivery_date, \invoice\sending_date )

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.

72Getting Started Guide Axway Mapping Services DML 3.0.1


Connections with Boolean operators

Symbolicvaluesabsentandnullarenotconcernedwithorder:testingorderwithabsentornull
resultsinundefinedbehavior.

Connections with Boolean operators


BuildingBooleanexpressionswithasingletestatatimecanproveabitcumbersome.Youmight
needtocombinemorethanonetesttodeterminewhatyouwant.Thisisaccomplishedusing
Booleanoperators.ABooleanoperatordoesnothingmorethanconnecttwoormoreBoolean
expressionstorepresentatrueorfalsevalue.

YoucanchooseamongfourBooleanoperatorsinDMLexpressions:and,or,xorandnot.

TheandoperatorcombinestwoBooleanexpressions.Itcanrepresentatruevalueonlyifbothleft
andrightexpressionsthatitconnectsalsoaretrue.Toshowhowtheandoperatorworks,people
thatworkwithcomputerssimilartodrawsomethingtheycallatruthtable,whichtellsyouwhatthe
resultoftheconnectedexpressionsis.Thefollowingisthetruthtablefortheandoperator:

Value of Value of Value of


left right left and right

False False False

True False

True False False

True True

TheoroperatorlinkstwoBooleanexpressionsbutproducesatruevalueifeitherBoolean
expressiononleftorrightrepresentsatruevalue.Thisoperatorcanproduceafalsevalueonlyif
bothofitsoperandsarealsofalse.

Thefollowingisthetruthtablefortheoroperator:

Value of Value of Value of


left right left or right

False False False

True True

True False True

True True

Axway Mapping Services DML 3.0.1 Getting Started Guide73


6 Making decisions with conditional statements

Theandandoroperatorshaveacloserelationshiptocommonsense.Askingyourselfwith
questionssimilartoDo I store the meat Ive just bought in the fridge or the freezer?
thatinvolvethewordsandororarequitethesameasusingtheoperatorsinexpressions.

ThexoroperatorconnectstwoBooleanexpressionsandreturnstrueifoneandonlyoneofthe
expressionsitconnectsistrue.Itisjustsimilartotheoroperatorexceptthathavingtwotrue
meansfalse:

Value of Value of Value of


left right left xor right

False False False

True True

True False True

True False

ThelastBooleanoperatoroperatesonlyononeBooleanexpression.Withthenotoperatoryoucan
reversethevalueofaBooleanexpression.Thismeansthattheresultingvalueisfalseiftheoriginal
wastrue,andtrueiftheoriginalwasfalse.

WithBooleanoperatorsyoucanconnectsingleteststobuildbiggerexpressionsthatturntrueor
falseincomplexsituations.Justsimilarto+,-,*and/operatorsinamathformula,and,or,xor
andnotcanbeusedasmanyasneededtomatchthecorrectsituation.Thefollowingisthe
completeexpressionthatdetectswhetherayearisaleapyear:

(remainder(%year, 4) = 0) and not(remainder(%year, 100) = 0)


or (remainder(%year, 400) = 0)

Thisexpressionevaluatestotrueonlywhentheyearisamultipleoffourwithoutbeingacentury,
exceptforcenturiesthataremultiplesoffourhundredtheremainderfunctionisusedto
determinewhetherayearisamultipleof4,100or400.

Whenperformingthisexpression,theintegrationenginefirstevaluatestheexpressiontowhichthe
notoperatorisapplied,thenitconnectstheresultswiththeandoperator,and,finallycomputes
theoroftheresultwiththelastpartoftheexpression.Similartobasicmathoperators,theorderof
evaluatingBooleanoperatorsisstrictlyruledbypriorityorder:

Highestpriority not and xor or Lowestpriority



processedfirst processedlast

74Getting Started Guide Axway Mapping Services DML 3.0.1


Testing conditions with if-then-else

Testing conditions with if-then-else


Themostcommonwaytocontrolwhichpartofanexpressionshouldbeactiveandwhichshouldbe
ignoredistousethe if then statement.Thisstatementcheckswhetheracertainconditionis
true.Ifitis,ittellstheintegrationenginetoactivateaspecificpartoftheexpressionthatwouldbe
otherwiseignored.

Theifthenstatementlooksasfollows:

if \invoice\date > '2005-12-31'


and \invoice\date < '2007-01-01' then
{
%invoices2006 = %invoices2006 + 1
}

Whenprocessingthisexpression,theintegrationengineevaluatestheBooleanexpressionbetween
ifandthenreservedwords.Iftheevaluationreturnstruethelistofstatementsenclosedbetween
thecurlybrackets{and}isevaluated,otherwiseitisignored.Thisistotestwhetherthedateofthe
invoiceiswithinyear2006.Ifso,oneisaddedtothecontentsofthevariableinvoices2006;asa
result,thenumberofinvoicesof2006isdetermined.

Whiletheifthenstatementisawaytoactivatesomepartofanexpressiononlywhenacertain
conditionistrue,theif then elsestatementtellstheintegrationenginetoevaluateoneset
ofinstructionswhentheconditionistrueandanothersetofinstructionswhentheconditionis
false.Hereisanexampleofthisstatement:

if \water\quantity > 1000 then


{
(\water\quantity / 1000) & " m3"
}
else
{
\water\quantity & " l"
}

Thisstatementbuildsthestring"32 m3"whentheinputquantityofwateris32,768and"234 l"


whentheinputquantityis234.Thelistofstatementsthatisenclosedbetweenthecurlybrackets{
and}canbeanyexpression.Specifically,itcancontainadditionalifthenelsestatements.In
computerterminology,itissaidthatifthenelsestatementscanbenested .

Axway Mapping Services DML 3.0.1 Getting Started Guide75


6 Making decisions with conditional statements

Advanced testing with switch


Listingmultipleconditionsinanifthenelsestatementcanprovetediousandmessy,asthe
followingexampleshows:

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"
}}

76Getting Started Guide Axway Mapping Services DML 3.0.1


Advanced testing with switch

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide77


6 Making decisions with conditional statements

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.

78Getting Started Guide Axway Mapping Services DML 3.0.1


Testing for the existence of a node

Testing for the existence of a node


Insomesituations,youmightuseambiguouspathstowriteshorterandmoreunderstandable
expressions.Youmightneed,forexample,tocheckthelengthofanIDthatisdefinedseveraltimes
inacomplexdocument.Suchanexpressioncouldbe:

if (length(\\id) <> 19)


{

}

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

Axway Mapping Services DML 3.0.1 Getting Started Guide79


6 Making decisions with conditional statements

Thesecustomerrecordsincludeadiscount_ratethatisnotpresentinsupplierrecords.Youcan
usethedefinedoperatortocheckwhethertheidisoneofyoursupplierorcustomer:

if (length(\\id[where defined item\..\discount_rate][1]) <> 19)


{

}

ThewhereclausematchesonlyforIDnodesthatdohaveasiblingnodenameddiscount_rate.
Whenprocessingadefinedoperatorstatement,theintegrationenginecheckswhetherthepaththat
followstheoperatorleadstospecifiednode.Ifso,thestatementisevaluatedtotrue,otherwise,the
valueisfalse.

Inthepreviousexample,statementsenclosedbetweenthecurlybracketsareevaluatedonlyfor
customerIDsthatarenot19characterslong.

Youcanreversetheconditionusingtheundefinedoperatorinthesameconditions.

FoodBroker project: Extra charge for


VISA payments
ForyourcompanyInstantTakeOut,paymentsmadewithVISAcardsimplyextracoststhatthe
companypassesontothecustomer.Inthissectionyouwillenhancetheexpressionyouenteredfor
totalamounttoaddextraVISAcharges.Todothis,useconditionalsasshowninthefollowing
expression:

if order:\order\payment = "VISA" then


{
if %amount * 1.05 < 75 then
%amount * 1.05 * 1.13
else
%amount * 1.05 * 1.015
}
else
%amount * 1.05

80Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Extra charge for VISA payments

Thisexpressionchargesthecustomerwithavariableratewheneverthepaymenthasbeenmade
usingaVISAcard.Thefollowingtabledescribesthedecisionconditions:

Payment condition Extra charges

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide81


6 Making decisions with conditional statements

Inthisgraphic,theroundfunctionisusedthattheresultofthecalculationswillfitintothedefined
fieldparametersoftotal.

82Getting Started Guide Axway Mapping Services DML 3.0.1


Repeating statements
with loops 7
Inproductionenvironments,thedatayoumapusingtheintegrationenginetendstobehighly
redundant.Youoftenneedtoexamine,combineandcheckeveryitemofahugeamountofdata,
repeatingthesamepatternwithinanexpression.

Naturally,executingthistypeofrepetitivetaskcanbeboringandpronetoerrors.Ideally,in
programmingyouprefertowriteexpressionsasconciselyaspossible,notonlybecauseshort
expressionsareeasiertodebug,understandandmodify,butalsobecausetheyrequirelesstyping.

Onewaythatcomputerlanguagessolvethisproblemisbyusingprogrammingstructuresknownas
loops.Basically,aloopisasortofstatementthatmakestheintegrationenginerepeatacertainset
ofstatements,thereforerequiringyoutoenterthemonlyonetimeinthecode.

Repeating a fixed number of times


Thepurposeofaloopistorepeatasetofstatements.Wheneveryoucreatealoop,youeventually
needtomaketheloopstop.Themostprimitivewaytodothisistospecifythenumberofloop
repetitions.

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide83


7 Repeating statements withloops

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

84Getting Started Guide Axway Mapping Services DML 3.0.1


Repeating a fixed number of times

Trace of evaluation

Line Evaluation

1 Valueofvariableaddresssettoemptystring""

2 Valueofvariableindexsetto1

3 Evaluationofcount(\\address\lines),resultis2

4 Enteringtheloop

5 Value"Sherlock Holmes"ofthe1 stoccurrenceoflinesispickedup


variableaddressisnowfilledwith"Sherlock Holmes"

6 Variableindexisincremented,newvalueis2

7 Checkingwhethertheloopends;atthistimetheloophasbeenperformedonly
onetimeoutoftwo,sogobacktoline4

4 Continuetheloop

5 Value"221b Baker Street"ofthesecondoccurrenceofnodelinesis


appendedtovariableaddressthatisfillednowwith:
"Sherlock Holmes221b Baker Street"

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide85


7 Repeating statements withloops

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.

86Getting Started Guide Axway Mapping Services DML 3.0.1


Handling irregularities: pass and abort

AconditionthatstopsawhileloopisaBooleanexpressionthatcanbeascomplexasneeded.
Rememberthatthisconditionischeckedateachrepetitionoftheloop,beforeanyofthestatements
includedintheloopareevaluated.Itispossiblethatthesetofinstructionsincurlybracketsmight
neverbeenevaluatedatall.

Usingwhileismoreflexiblethanusingloop,butcanpresentrisks.Oneofthemostcommon
problemswithsuchloopsisknownasendlessloops,whichmeansthattheintegrationengine
evaluatesthesetofstatementsincludedintheloopbutneverstops.Iftheintegrationengineis
caughtinanendlessloop,itmightseizeandexhaustallthehostresources,forcingyouto
reinitializetheserver.

Themaincauseofendlessloopsisaninappropriatestopcondition.Whenyouusewhile,make
surethattheconditionwillatsomepointbecomefalse.

Handling irregularities: pass and abort


Normally,theonlywaytoexitaloop(whetherwhileorloop)istowaituntileitherthespecified
numberoftimeshasbeenrepeated,orthesuppliedconditionturnstofalse.Insomesituations,you
mightwanttoexitaloopprematurelyortogodirectlytothenextrepeat.

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide87


7 Repeating statements withloops

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.

88Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Introduction to data aggregation

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.

FoodBroker project: Introduction to data


aggregation
Thedatathatissenttotherestaurantorderapplicationincludesapieceoftextthatcontainsthe
order.Thistextisactuallythemessagebodyofthefaxsenttothepartnerrestaurant.Thistextis
composedoflinesthatincludetheordereddishandthequantityrequired.Youcanexplicitly
concatenatealltheitemsusingpathswiththe[]operatorandstringoperator+:

order:\order\line[1]\qty + " x " + order:\order\line[1]\!item! + "\n" +


order:\order\line[2]\qty + " x " + order:\order\line[2]\!item! + "\n"

Axway Mapping Services DML 3.0.1 Getting Started Guide89


7 Repeating statements withloops

Thisexpressionworks,butignoresorderlinesafterthe2 nd .Thisisnotacceptable:youneedtotake
intoaccountalloccurrencesofthelinenodetobuildthecompletetext.Aloopisneeded.The
expressionthataccumulatesalltheorderlinesintothetextis:

%text := ""; %line_index := 1;


loop (count (order:\\line))
{
%text := %text + order:\order\line[%line_index]\qty
+ " x " + order:\order\line[%line_index]\!item! + "\n";
%line_index := %line_index + 1
};
%text

Thisworksfinefororderswithlessthanonehundredlines,butbecomeslessandlessefficientasthe
numberoflinesgrows.Whatistimeconsuminginsuchastructureisthattheintegrationengine
doesnottodetectthatyouactuallywanttopickupoccurrencesoflineoneafteranother.Inthis
situation,eachaccesstolinerestartsfromtheveryfirstoccurrence.Thetimeneededtoperform
thisloop on n occurrencesisroughlyproportionalton.

Abettersolutionisshowninthenextchapter.

90Getting Started Guide Axway Mapping Services DML 3.0.1


Handling multiple
occurrences 8
NextisthemosttrickybusinessinusingDML:advancedprocessingofmultipleoccurrences.Ina
previoussectionofthisguideyoulearnedaboutcardinalitiesandyousawexamplesofwaysto
selectoccurrencesofaspecificnodeamongalltheexistingoccurrences.

Inthefollowingpages,youwillgoonestepfurther.Thefollowingquestionsareanswered:

l HowdoImapthroughasetofoccurrences?

l HowdoIgenerateasmanyoccurrencesasrequiredbytheoutputBusinessDocument
definition,orasmanyasdoexistintheinput?
l HowdoIcopyacompletetreeofinputnodesverbatimtotheoutput?

Going through occurrences


Inthepreviouschapter,yousawanexamplethatcompoundedthecomponentsofanaddressintoa
singlestring.Thiswasaccomplishedusingabasicloopandapathcontainingthebracketoperator
toretrieveasingleoccurrenceofanode.

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

Axway Mapping Services DML 3.0.1 Getting Started Guide91


8 Handling multiple occurrences

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.

92Getting Started Guide Axway Mapping Services DML 3.0.1


Generating a fixed number of occurrences

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:

loop on \\CTA, \\COM


{

}

ThiscodegoesthroughalloccurrencesofallCTAsegmentsandthenalloccurrencesofCOM
segments.Intherepeatedsetofstatements,thisrefersfirsttoCTAnodesandthentoCOMnodes.

Similartostandardloopsandwhileloops,loop onstatementscanincludeanotherloopinsidethe
setofstatementstheyrepeat.Insuchasituation,thekeywordthisalwaysreferstotheinnerloop.

Generating a fixed number of


occurrences
Expressionsareusedmainlytoperformmappingsondata.Theintegrationenginepicksupand
combineselementsfromtheinputdatatogeneratenewoutputdata.Thisisaccomplishedby
bindinganexpressiontoeachofthenodesoftheoutputBusinessDocument.

Axway Mapping Services DML 3.0.1 Getting Started Guide93


8 Handling multiple occurrences

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

94Getting Started Guide Axway Mapping Services DML 3.0.1


Generating a fixed number of occurrences

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

Axway Mapping Services DML 3.0.1 Getting Started Guide95


8 Handling multiple occurrences

Whatchangeshere,isthatthesegmentholdsanumber(thefirstoccurrenceis1andthesecondis
2)anda,bandcarenowattributes.Youmustusetimesdoinconjunctionwithavariablein
ordertonumberthesegments:

Output Bound expression


node

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.

96Getting Started Guide Axway Mapping Services DML 3.0.1


Generating occurrences from occurrences

Generating occurrences from


occurrences
InsectionGoingthroughoccurrencesonpage91youlearnedhowtogothroughasetof
occurrences.InsectionGeneratingafixednumberofoccurrencesonpage93youlearnedhowto
generateasmanyoccurrencesasneededtomeetthecardinalitiesdefinedintheoutput.Now,
discoveratoolthatcombinesthesetwofunctions,goingthroughasetofoccurrencesand
generatingasmanyasdetected.

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:

Output node Bound expression

invoice

line for each \\line

item_id this\item_id

quantity this\quantity

unit_price this\unit_price

amount this\quantity * this\unit_price

Axway Mapping Services DML 3.0.1 Getting Started Guide97


8 Handling multiple occurrences

Whileprocessingtheexpressionboundtotheoutputnodeline,theintegrationenginecountsthe
numberofoccurrencesoflineintheinputandcreatesthatnumberofoccurrencesoflineinthe
output.

Eachtimeanoccurrenceoflineintheoutputiscreated,theintegrationenginecreateseach
memberoftheoutputgrouplineusingthecorrespondingboundexpression.Asaresult,the
membersitem_id,quantityandunit_pricearecopiedfromtheinput.Noticetheuseofthisto
refertothecurrentinputnodeline.Theoutputvalueamountiscomputedusingvaluesunit_
priceandquantityretrievedfromtheinput.

Thefollowinggraphicillustratesthetasks,withexampledatavaluesillustrated:

for each dostatementextendstheforeachstatementthesamewaytimesdoextendstimes.If


theoutputnodelineshasbeendefinedashavingavaluethatnumbersthelines,youwould
appendthesamedoasyoudidwhennumberingsgroups.

98Getting Started Guide Axway Mapping Services DML 3.0.1


Questioning loop progress

Unsimilartotheloop onstatement,for eachisnotarealloop.Thisiswhybreakandnext


instructionscannotbeusedtointerferewiththeoccurrencescoverage.However,youcanuse
ambiguouspathsandfilterstodefinethesetofnodeoccurrencesyoucover.Inaddition,morethan
onepathcanbestatedtoenlargethesetofnodesandoccurrencesthatyouwanttogothrough.

Allcardinalitiesandloopstatements(loop,loop on,while,timesandfor each)canbenested


andmixedasyourequire.Aslongasyouaddressexistingnodesandbindexpressionsappropriately,
youarefreetousethesestatements.Thereservedwordthisalwaysreferstothenearestloop onor
for each.

Whennestingfor eachand/orloop on,youcanuseapathstartingwiththisinaninnerfor each


and/orloop on.Thismeansthattheinnergoesthroughsomethingrelatedtothecurrentnodeor
occurrenceoftheouter.

Questioning loop progress


Youknowhowtogothruasetofoccurrencesusingloopandfor eachstatements.Whenusing
suchconstructions,youwillquicklydiscoverthatknowingonwhichelementintheexplored
collectionyouareisquiteessential.Inmostsituations,eitherthefirst(orlast)elementhas
somethingspecialoryouneedtheindexofthecurrentelement.

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide99


8 Handling multiple occurrences

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

Copying parts of inputs: The tree


instruction
Whendealingwithverylargedocuments,itcanbetimeconsumingtocreateDMLBlocksthatcopy
partsoftheinputdirectlytotheoutputusingfor eachstatements.Furthermore,therepetitious
executionofthesestatementsconsumesprocessingresources.

Tobemoreefficient,youcanusethetreestatementtoperformblindcopiesofasub-treeofnodes
fromtheinputtotheoutput.Atreestatementiscomposedofthereservedwordtreefollowedbya
pathtoanode.Thenodethatyoureferenceinthestatementcangrouptogetherotherdependent
nodesandgroups.Atreestatementisalwaysthesinglestatementofanexpression.Thisis
commonlyreferredtoastreeexpressionsratherthantreestatements.

Whenyoubindatreeexpressiontoanoutputnode,youtelltheintegrationenginetocreatethe
outputnodefromadirectandcompletecopyoftheinput.Iftheoutputnodegroupsothernodes,
allexpressionsboundtothosenodesareignored.

100Getting Started Guide Axway Mapping Services DML 3.0.1


Selecting children of a CHOICE parent

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.

Selecting children of a CHOICE parent


WhendefininganXMLBusinessDocument,youcancreateparentsofaspecialkindcalledchoice
parents.SuchparentsaresimilartoCHOICEelementsinXMLSchemas:theyallowonlyoneofthe
nodestheycontaintobepresentwithinthecontainingnode.

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide101


8 Handling multiple occurrences

Maybe,yourintuitionwouldtellyoutousetimesdostatementsoneachchildtoalternatively
generatephone,cellularoremail.Thiswontworkintheintegrationengine.Selectioniscentralized
intheintegrationengine:theexpressionattachedtothechoicenodedefineswhichchildto
generateandexpressionsattachedtochildrendeterminetheirvalue.Thefollowingisanexampleof
aMaptogeneratedeliverynotesfromaninputdocument:

Output node Bound expression

contactRecord for each in2:\contact[where item\name =


in1:\customer\name]

choice switch (this\contactTypeId)


{
case 0,1,8:
{ select 1st }
case 10 to 50:
{ select 2nd }
case 99:
{ select 3rd }
default:
{ exit reject }
}

phone this\data

cellular this\data

email this\data

Inthatexample,thedocumentfrominputin1containsthenameoftheaddressedcustomerwhile
thecontactinformationiscarriedbythedocumentfromtheinputin2.

TheexpressionattachedtocontactRecord selectscontactinformationfromin2 documentusing


thecustomername.Contactinformationfromin2 isasetofrecordsthatcontainthenameofthe
customer(name node)alongwiththeidofthetypeofcontact(contactTypeIdnode)andthe
contactdataitself(data node).

102Getting Started Guide Axway Mapping Services DML 3.0.1


Selecting children of a CHOICE parent

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide103


8 Handling multiple occurrences

FoodBroker project: Collecting and


copying parts
Thetoolloop oninstructionimprovestheefficiencyoftheexpressionsforgeneratingthefaxtext.
Thefollowingisanimprovedversionoftheexpression:

%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.

104Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Collecting and copying parts

Forcustomerandsupplierlines,yougenerateasmanylinenodesintheoutputasthereexistline
nodesintheinputwiththeinputvaluesinthem.Toaccomplishthis,youuseafor eachdo
structureastheexpressionboundedtolineintheMap:

for each order: \order\customer\address\line do this


for each order: \order\supplier\address\line do this

Thefirstexpressionisforalinenodewhichresidesinthecustomergroup.Thesecondexpression
isforalinenodewhichresidesinthesuppliergroup.

Forlinenodesintheorder,thetechniqueisquitesimilar:youusefor eachontheparentitem.
Whenprocessingthefollowingexpression,thatisattachedtothenodeline(node#33inthe
followinggraphic),theintegrationenginegeneratesasmanyoccurrencesoftheoutputgroupline
asthereareoccurrencesoftheinputgroupline:

for each order: \order\line

Thismeansthatitem(#34),qty(#35)andprice(#36)nodesaregeneratedusingtheir
expressionsintheMap.

Axway Mapping Services DML 3.0.1 Getting Started Guide105


8 Handling multiple occurrences

Intheprecedinggraphic,youcanseehowthecopyisperformed:

l Theexpressionfortheparentlinecontainsaforeachstatementthatgeneratesasmanygroups
asneeded
l Eachgroupmemberhasanexpressionthatgeneratesitsvaluefromthecurrentlinenodevalue
intheinput(referredtobythekeywordthis)
Noticetheuseofexclamationmarkstokeepthenodenameitemfrombeinginterpretedasthe
keyworditem.

Iftheincomingorderfromthewebserverincludesemptylines(eitheremptyitemsorzero
quantities)andyoudonotwantemptyvaluenodesintheoutputBusinessDocument,addafilter
usingawhereclause:

106Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Collecting and copying parts

ThefinalnodethatyouneedtocomputeforbothoutputBusinessDocumentsistheinitialamount
oftheorder.Thisisbasicallythesumofthelinecostsofeachorder,whichforeachlineisthe
quantitymultipliedbytheunitprice.

Youneedtogothroughalltheoccurrencesofline,performthemultiplication,andaccumulatethe
resultsinavariablethatthenrepresentsorderamount.

Thefollowinggraphicillustratesappropriateexpressionboundtotheamountnode:

Axway Mapping Services DML 3.0.1 Getting Started Guide107


8 Handling multiple occurrences

108Getting Started Guide Axway Mapping Services DML 3.0.1


Extending DML with
Custom Functions 9
Inthepreviouschaptersofthisguide,youhaveseenmostofthestandardfunctionalitysuppliedby
DMLintheintegrationengine.IfyoutakeaquicklookattheDMLonlinehelpyourealizethatthe
possibilitiesofDMLgofarbeyondthissetofnativeDMLtools.

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide109


9 Extending DML with Custom Functions

Using a function: function calls


Usingafunctionisknownascallingafunctionincomputerterminology.Becausetheserviceyour
functionprovidesmightneedinputinformationthatisdifferentateachcall,youcansupplyitwith
parameters.Becauseitreturnsavalue,afunctioncallissimplyanothertypeofexpression,similarto
thearithmeticorBooleanexpressionsdiscussedearlieringuide.Infact,youcancombinefunction
callsandoperatorstocreatemorecomplicatedexpressions.

Callingafunctioninanexpressionisassimpleasquotingitsnamefollowedbythelistofparameters
enclosedbetweenparenthesis.Parameterscanbeexpressionsandareseparatedwithcommas.

Asanyintegrationengineobject,CustomFunctionsarereferredtousingeitherafully-qualified
nameorashortname,shownasfollows:

myentity.commonstuff\calendar.IsLeapYear(%year)
commonstuff\calendar.IsLeapYear(%year)
IsLeapYear(%year)

Youhavealreadyseenexamplesoffunctioncallspreviouslyinthisguide:

(remainder(%year, 4) = 0) and not (remainder(%year, 100) = 0)

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.

110Getting Started Guide Axway Mapping Services DML 3.0.1


About functions

TodefinetheIsLeapYearCustomFunction:

1. InAxwayMappingServicesworkbench,intheleftframe,selecttheExtended Objectsfolder
andthentheFunctionssubfolder.
2. Usethecontextmenutocreatethenewfunction:

3. Fromthecontextmenu,yougetthefollowingwizard:

4. Followthewizardandchoosethecategoryofthefunctionandafternextthenameofthe
function.ClickonFinish.
5. IntheParameterstab,thatyoucanaccessbydouble-clickonthenewfunction,definethe
functionparametersifneeded.

Axway Mapping Services DML 3.0.1 Getting Started Guide111


9 Extending DML with Custom Functions

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.

112Getting Started Guide Axway Mapping Services DML 3.0.1


About functions

Thismeansthatyouhavecertainuselimitations:thefollowingtablelistsexamplesofacceptable
andunacceptablecalls:

IsLeapYear("1987") not ClassSofrealargument"1987"isnot


OK compatiblewithclassIofformalargument
year.

IsLeapYear(1963+true) OK TheBooleanliteraltrue ispromotedtothe


wholenumber1thenaddedto1963to
obtain1964whichisanacceptableclassI
valueforparameter.

4*IsLeapYear(1987) OK ClassBofthevaluereturnedbythefunction
canbeconvertedtoclassItoperform*.

"leap:" + IsLeapYear OK Thereturnedvalueisimplicitlypromotedto


(1988) thestring"1"whichisappendedto"leap:"
forformthefinalstringleap:1.

Axway Mapping Services DML 3.0.1 Getting Started Guide113


9 Extending DML with Custom Functions

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.

114Getting Started Guide Axway Mapping Services DML 3.0.1


Implementing Custom Functions in C

Implementing Custom Functions in C


YoucanextendDMLusingCprogramminglanguage.WhenyoudefineaCustomFunction,youcan
chooseCforitscategory.Thismeansthattheintegrationengineexpectsthefunction
implementationtoresideinadedicatedsharedlibrarycalledlibXIBcf.so( Unix)orlibXIBcf.dll
(Windows).

Unexpectedly,youcanuseanyprogramminglanguagetoimplementaCCustomFunction,
provideditcomplieswiththeCcallingconventionandthestandardABIforthehostonwhichthe
integrationengineserverruns.Thebasicservicesthatyouneedforembeddingyourfunctioninto
thewholeintegrationengineserveraresuppliedasaC-languageAPI.

Getting an overview
ThebasicstructureofaCustomFunctionwrittenusingCprogramminglanguageisshowninthe
followingdiagram:

Envelopingthecodethatperformsthecoreprocessingcodeofthefunctionaretwolayersthat
extractthevaluesoftherealparametersandgeneratethereturnvalue.Thesearenecessarybecause
oftheuseinintegrationengineofabstractcontainersforparameters.

Axway Mapping Services DML 3.0.1 Getting Started Guide115


9 Extending DML with Custom Functions

ConsidertheIsLeapYearCustomFunctionwhichdetermineswhetherasuppliedyearisaleapyear
ornot.TheCprototypethatmatchesthedefinitionmadepreviouslyis:

void IsLeapYear(xibrt_handle hCtx, xibrt_handle hValue,


xibrt_handle hYear)

ThefirstargumentofaCustomFunctionisalwayshCtx,whichshouldbepassedwithoutany
changetoallsubsequentcallstotheintegrationengineruntimeserviceslibrary.Theremaining
argumentsarethefunctionreturnvalueanddefinedparameters.Eachoftheseisahandleson
containerthatcontainthevalues.

Exchanges between containers and


standard C types
Theintegrationengineruntimeserviceslibrarysuppliesthefunctionsthatcollectvaluesfromthe
integrationenginecontainersorfillthemwithvalues.Basicallythesefunctionstranslatehandles
intoC-typedvaluesinbothdirections(write/retrieve).ApairoffunctionisavailableforeachDML
class.

Thefollowingtabledescribesthematchingbetweentheclassandthewriteandretrievefunction
names;thestandardCtypethatcorrespondstotheclassisalsoshown:

Class Retrieve function Write function C-Type

B xibrt_getBoolean xibrt_setBoolean int

I xibrt_getInteger xibrt_setInteger long

R xibrt_getFloat xibrt_setFloat double

D xibrt_getDate xibrt_setDate struct tm

S xibrt_getString xibrt_setString char *

V xibrt_getBinary xibrt_setBinary char *

Retrievefunctionsforscalartypes(B,I,RandDclasses)allfollowthesamesignaturemodel:

/* Scalar types retrieving functions */


int xibrt_getBoolean(xibrt_handle hCtx, xibrt_handle hSource);
long xibrt_getInteger(xibrt_handle hCtx, xibrt_handle hSource);
double xibrt_getFloat(xibrt_handle hCtx, xibrt_handle hSource);
struct tm xibrt_getDate(xibrt_handle hCtx, xibrt_handle hSource);

116Getting Started Guide Axway Mapping Services DML 3.0.1


Implementing Custom Functions in C

Retrievingstringsorraw-dataarisestheproblemofallocatingenoughroomtoreceiveacomplete
copyofthedateread.Afunctionisprovidedthatreturnsthememorysize(inbytes)neededtohold
theretrieveddata:

/* Retrieving memory sizes */


size_t xibrt_getSize(xibrt_handle hCtx, xibrt_handle hSource);

Thisfunctioncanbeappliedtoanycontainerandreturnsasizeinbytes.Thefollowingtableshows
sizesreturnedbythiscallinseveralsituations:

Platform Container Function returns


class

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);

}

Axway Mapping Services DML 3.0.1 Getting Started Guide117


9 Extending DML with Custom Functions

Bothstringandraw-dataretrievingfunctionsusethesamemodelasfollows:

/* String and raw-data types retrieving functions */


size_t xibrt_getString(xibrt_handle hCtx, xibrt_handle hSource,
size_t nTargetSize, char *pszUTF8Target);
size_t xibrt_getBinary(xibrt_handle hCtx, xibrt_handle hSource,
size_t nTargetSize, char *pTarget);

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);

118Getting Started Guide Axway Mapping Services DML 3.0.1


Implementing Custom Functions in C

Thiscodecanbeverytimeconsuming.IfyourIBANstringsareencoded,forexample,inEBCDIC,
theintegrationengineconvertsthemtwice:

l FromEBCDICtoUTF8whenthestringisretrievedusingxibrt_getString
l FromUTF8backtoEBCDICwhentheedstringisgivenbacktohIBANusingxibrt_setString.
Thepreviouspieceofcodeusesoneofthewritefunctionsthatplacesdataintoanexisting
container.Asexpected,writerfunctionsforscalartypesarenatural:

/* Scalar types writing functions */


void xibrt_setBoolean(xibrt_handle hCtx,
int iSource, xibrt_handle hTarget);
void xibrt_setInteger(xibrt_handle hCtx,
long lSource, xibrt_handle hTarget);
void xibrt_setFloat(xibrt_handle hCtx,
double dSource, xibrt_handle hTarget);
void xibrt_setDate(xibrt_handle hCtx,
struct tm tSource, xibrt_handle hTarget);

Concerningwriterfunctionsforstringsandraw-data,youmustsupplyabufferaddressandthe
lengthofsignificantdataitcontains,inbytes:

void xibrt_setString(xibrt_handle hCtx,


size_t nSourceSize, char*pszUTF8Source,
xibrt_handle hTarget);
void xibrt_setBinary(xibrt_handle hCtx,
size_t nSourceSize, char *pSource,
xibrt_handle hTarget);

Afteragain,thesystemassumesthesuppliedstringisUTF8encoded.

Thesourcelengthcanbelessthantheactualsourcebuffersizebecauseonlysignificantdata
(includingfinal\0forstrings)isconsidered.

Containers and symbolic values


Whendealingwithsymbolicvaluesnullandabsent,thepreviousfunctionsarenotappropriate.A
pairoffunctionsareavailabletodeterminewhetheracontainerholdsanullorabsentvalue;
anotherpairoffunctionsenableyoutomakeacontainertoholdsuchasymbolicvalue.

/* Testing against null or absent */


int xibrt_isNull(xibrt_handle hCtx, xibrt_handle hSource);
int xibrt_isAbsent(xibrt_handle hCtx, xibrt_handle hSource);

/* Making null or absent */


void xibrt_setNull(xibrt_handle hCtx, xibrt_handle hSource);
void xibrt_setAbsent(xibrt_handle hCtx, xibrt_handle hSource);

Axway Mapping Services DML 3.0.1 Getting Started Guide119


9 Extending DML with Custom Functions

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:

/* Last call status */


int xibrt_getLastStatus(xibrt_handle hCtx);

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.

120Getting Started Guide Axway Mapping Services DML 3.0.1


Working with SQL Custom Functions

Onlyoneheaderinclusionisrequired.Thisheaderhasnodependencieseitheragainstanother
suppliedheaderoranysystemheader.Theonlyrequirementisthefollowinglineinyourcode:

/* Include Integrator runtime services */


#include "XIBRT_Interface.h"

AllthesefunctionsarecontainedinadedicatedsharedobjectnamedlibXIBrt.soonUnices,and
libXIBrt.dllonWindows,whichresidesinthebinsubdirectoryofyourintegrationengineserver
installation.

WhenbuildinglibXIBcf.soyoumustlinkwithlibXIBrt.soandanyoftherequiredthird-party
libraries.RememberthatlibXIBcf.sowillbeloadedonlywhenrequired:nocalltouser-defined-
function,nolibraryloading.YourlibraryforCustomFunctionsmustbeloadablebyimplicitdynamic
link.itisagoodpracticetoplaceitintothebinsubdirectoryofyourintegrationengineserver
installation.

Working with SQL Custom Functions


Insomeintegrationengineprocessingcontexts,youmightneedtoretrieveinformationtousein
DMLexpressionsfromanexternalDBMSsuchasOracleorMySQL.Onewaytoachievethisistowrite
afunctionusingtheCprogramminglanguageinconnectionwithyourDBMSaccesslibraries.

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:

SELECT CODE FROM ZIP WHERE CITY = #city_name#

Axway Mapping Services DML 3.0.1 Getting Started Guide121


9 Extending DML with Custom Functions

WhentheintegrationengineexecutestheCustomFunction,itreplaces#city_name#withthe
valueofthefunctionparametercity_nameenclosedindoublequotes,andreturnsthevalueofthe
codefromthetable.

ThefollowinggraphicillustratesthecontentoftheImplementation tab:

Forsuchfunctionstobesuccessfullyexecuted,youmustdefineaJDBCChannelinAxwayMapping
ServicesthataddressestheappropriateDBMS.

Working with Java Custom Functions


InadditiontoCprogramminglanguageandSQL,youcanuseJavaprogramminglanguagetowrite
thebodyofyouruser-definedfunctions.AsforimplementationsinC,declaringCustomFunctions
usingJavarequiresathird-partytool.Specifically,youhavetoinstallaJDK(compatiblewithJVM
1.5)onthehostwhereyouintendtodevelopyourCustomFunctions.

Basically,thebodiesofyourownfunctionsareanimplementationoftheFunctioninterfacethatis
suppliedwiththecom.axway.xib.api.dml.Functionpackage.Whenwritingthebodyofyour
JavaCustomFunction,youcreateanewclassthatimplementstheinterfaceandcontainsamethod
forthebodyofyourfunction.

122Getting Started Guide Axway Mapping Services DML 3.0.1


Working with Java Custom Functions

ThefollowingisapieceofJavacodefortheIsLeapYearCustomFunction:

import com.axway.xib.api.dml.Function;

public class CalendarHelper implements Function


{
public Object IsLeapYear(Object[] args)
{
if (args[0] == null)
{
return null;
}
int iYear = ((Integer) args[0]).intValue();
boolean bIsLeapYear = (iYear % 4 == 0 && iYear % 100 != 0)
|| (iYear % 400 == 0)
return new Boolean(bIsLeapYear);
}
}

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide123


9 Extending DML with Custom Functions

Afteryouvewrittenyourfunction,youusetheJavacompilertocompileit:

javac -classpath $CORE_ROOT/java/lib/dml-mapper-java-api-x.y.z.jar


MyFunctionClass.java

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.

FoodBroker project: Managing rates


SofarinyourprojectyouhavecompletedtheMB_extractorDMLBlock:theDecision-Pathandthe
twoMapsarecompletelyfilled.AllthenodesofalltheoutputBusinessDocumentsaregenerated
withtheappropriatenumberofoccurrencesandvalues.

Theonlyremainingtaskisthepartnerratesfeeding.IfyoureferbacktochapterIntroducingDMLon
page9,youllseethatthisfeedinginvolvesanetworkofDMLBlocks.

ThefirstDMLBlock(MB_tableLoader)isactivatedbyastarteventthatistriggeredeachtimea
newmessageisfedtotheDMLBlockinput.TheDMLBlockloadstheXMLfilethatcontainstherates.

ForthisDMLBlockyouneedtodefineonlyaDecision-PaththatactivatesaMap.ThetaskoftheMap
istoloadthefileintotheVclassnodeoftheoutput.

ThisMapusestheLoadFileCustomFunctiontoaccomplishtheloadingtask.Basically,thisCustom
Functionopensafile,placesthefilecontentintothereturnedVvalue,andthenclosesthefile.If
thefileisnotfound,theCustomFunctionreturnsabsent.

124Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Managing rates

LetshavealookattheCcodethatperformsthistask:

Axway Mapping Services DML 3.0.1 Getting Started Guide125


9 Extending DML with Custom Functions

int LoadFile(EXE_HANDLE hCtx,


EXE_hRegister hFileContents,
EXE_hRegister hFileName)
{
char szFileName[MAXPATH + 1];
FILE *pFile;
char *pBuffer;
size_t ulSize;

/* Reject calls with an empty filename */


if (xibrt_isNull(hCtx, hFilename) || xibrt_isNull
(hCtx, hFilename))
{
xibrt_setNull(hCtx, hFileContents);
return XIBRT_SUCCESS;
}
/* Extract filename arguments
* The contents of hFileName is cloned into a static buffer
* theoricaly large enough to contain the whole filename.
*Only a loss of data is possible here (truncated filename)
*that occurs only when the filename is not filesystem
*compatible.
*/
xibrt_getString(hCtx, hFileName, sizeof(szFilename),
szFilename);

/* Try to open the file and return absent on failure */


pFile = fopen(szFilename, "r");
if (!pFile)
{
xibrt_setAbsent(hCtx, hFileContents);
return XIBRT_SUCCESS;
}

/* Collect file size and allocate room for contents,


then load the file into the buffer and close it */
ulSize = fseek(pFile, 0, SEEK_END);
fseek(pFile, 0, SEEK_SET);
pBuffer = (char *) malloc(ulSize);
if (!pBuffer)
{
xibrt_setAbsent(hCtx, hFileContents);
return XIBRT_SUCCESS;
}
ulSize = fread(pBuffer, 1, ulSize, pFile);

126Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Managing rates

fclose(pFile);

/* Copy the file contents into the result blob */


xibrt_setBinary(hCtx, ulSize, pBuffer, hFileContents);

/* Perform some cleanup and return success */


free(pBuffer);
return XIBRT_SUCCESS;
}

AfteryouvecompiledthiscodecompiledanddefinedtheCustomFunction,thefunctionis
operationalandcanbeusedatruntimetoloadyourfile.Thesecondstageofthefeedingis
accomplishedbyanotherDMLBlock(MB_tableBuilder)thatparsestheXMLfileandgeneratesthe
correspondingBusinessDocument.

IntheDecision-PathoftheMB_tableBuilderDMLBlockyoucreateaparsestepthatgeneratesa
BD_partnerRatesBusinessDocumentinstancefromtherawdatanodeoftheinputBusiness
Document:

Now,yourMB_extractorDMLBlockiscorrectlyfedwiththepartnerrates.Theprojectiscomplete.

Axway Mapping Services DML 3.0.1 Getting Started Guide127


9 Extending DML with Custom Functions

128Getting Started Guide Axway Mapping Services DML 3.0.1


Exceptions
10
Whenwritingcomputerprograms,itisusuallypossibletodiscernbetweenthenormalcourseof
eventsandsomethingthatisoutoftheordinary.Unexpectedeventscanbeerrorsorsimply
somethingyoumightnotexpecttohappenveryoften.

ThischapterdiscusseshowtohandleexceptionaleventswhenmappingdatainDMLexpressions.

Making things go wrong your way


Tohandleexceptionalconditions,youmightuseconditionalstatementsineachplacethatthe
eventsmightoccur.However,forverylargeandcomplexexpressions,thiswouldmakeyourtext
inefficientandhardtoread.Torepresentexceptionalconditions,DMLusestheconceptof
exceptions.

Basicallyanexceptionisanalarmthatissetoffwhensomethingunusualhappens.Youstillneedto
useaconditionalstatementtodetecttheevent,butwhentheconditionismet,theintegration
engineraisesthealarm,abortstheprocessingoftheinputdataandeitherdiscardsorrejectsthe
dataithadjuststartedtocompute.

Settingoffthealarmisknownasraisinganexceptionandisdonebyinvokingthespecial
instructionexitwithasingleargumentthatstateswhichbehaviortheintegrationenginemustadopt
tohandlethealarm:

Exit argument Behavior adopted by the engine

reject Whenreceivingthisexception,theserverabortsthecurrent
processinganddirectlygoesonthenextone.

rejectMessage Theintegrationengineserverrejectsthemessagecurrentlyprocessed,
theneitherwaitsorprocessesthenextincomingmessage

Hereisanexampleofanexpressionthatrejectsamessageonacertaincondition:


if CheckIBAN(this\\IBAN_Code) then
{
exit rejectMessage
}

Axway Mapping Services DML 3.0.1 Getting Started Guide129


10 Exceptions

Wheneveranexitisencounteredandexecuted,theserverabortswhatitwascurrentlydoing.
Usually,thisleadstothecancellationofseveralpartsofthecurrentdataprocessing.Exception
handlingreliesonacompletetransactionalenginethatisabletovalidateorcanceldatageneration
operationsaccordingtothesituation.

How the system handles exceptions


Asstatedbeforeinthisdocument,MappingFlowsarenetworksofDMLBlocksthatarededicatedto
mappingdatacontainedintheinputdocument.Insomesituationsyoumightwanttoperform
certaintaskseitherbeforeanypartoftheinputisprocessed,orafterthewholeinputhasbeen
processed.

Events and exceptions


SucharequirementcanbehandledusingspecialDMLBlockscalledevents.Youcandefinethree
typesofeventsinaMappingFlow:thestartevent,theerroreventandtheendevent.Asyoumight
guess,startandendeventsareexecutedbeforeandafterinputisprocessed,anderroreventsare
executedwhenanerroroccurs.

Thefollowingdiagramshowshoweventstakeplaceinthewholeprocessofinputdataandoutput
generation.

Startandendeventsaretypicallyusedeithertoparticipateinenvelopegeneration(forexample:the
starteventgeneratesthefinalmessageheaderwhiletheendeventbuildsthefinalmessagetrailer)
orforloggingpurposes(tokeeptheuserinformedoftheprogressoftheprocess).

YouuseerroreventstorecoverfromerrorconditionsusingDMLcode.Forexample,youcanusean
erroreventtoextracterroneousdatafromthemaindatastreamandsendittoaspecialoutput.Error
eventsprovideanextensionofsomeaspectoftheregulardataprocessing.Thisiswhy,inthe
diagramabove,theyaresymbolizedusingthesamecolor.

130Getting Started Guide Axway Mapping Services DML 3.0.1


How the system handles exceptions

Asthediagramsuggests,withaMappingFlowandanerroreventappropriatelydefined,youare
abletoprocessspecificallyfaultypartsoftheinputdatawhilenormallyprocessingtheotherparts.
Whenthebadpartisprocessedanerrorconditionisdetectedandcontrolistransferredtotheerror
event.Whenthiserroreventhasbeenexecutedandprovidedtheerrorrecoveringisactive,control
istransferredbacktotheregularprocessingchain.

Severalfamiliesofsituationsleadtoanerrorconditionandtriggertheerroreventwhendefined:

l Invalid input or output data


Inputdataprocessedandoutputdatageneratedmightbecheckedagainstasetofrules.When
youactivateeitherFacetCheckorValidationRulesexecution,anyfailureisanerrorcondition.
l Run-time errors
Whilemappingdatamanyrun-timeerrorscanoccur.Mainlytheseareconversionproblems:
illegalinstructions(zero-division),systemresourceexhaustionorthird-partycomponent
failures.
l The exit instruction
UnliketothepreviousdescribedfamilieswhichrepresentautomaticbehavioroftheXIBengine,
theexitinstructionistheuser-definedwaytotriggererrorevent.
Whenanerrorfromoneofthesefamiliesisdetected,thecurrenttransactionisalwayscanceledand
thencontrolcanbetransferredtotheerrorevent.

Mapping Flow transactions


Inintegrationengineterminology,atransactionisasetofoperationsthatisconsideredasasingle
consistentblockandiscompletedorcanceledasawhole.

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide131


10 Exceptions

Furthermore,inputdataprocessedbytheMappingFlowcanbecomposedofseveralchunksofdata
calledinstances.Usually,allinstancesareprocessedwithinasingletransaction(theinstance
transaction)butwhenerrorrecoveringisactive,atransactioniscreatedforeachprocessed
instance.ErrorrecoveringisafeatureoftheMappingFlowthatyouactivatebycheckingcontinue
on errorintheFlow propertieswindowintheAxwayMappingServices.

Thefollowinggraphicshowswhentransactionsarestarted,completedorcanceledinseveral
situations:

Althoughallsituationsinthisgraphicshowbothstartandendtransactions,thisisnotmandatory:
starteventsandendeventsareoptional.

132Getting Started Guide Axway Mapping Services DML 3.0.1


How the system handles exceptions

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).

Impact of reject levels and exit


localizations
WhenexecutingaDMLBlockoranevent,thefollowingendingsarepossible:

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide133


10 Exceptions

Asaconsequence,whenerrorrecoveringisenabled,aglobalrollbackoperationmightbe
performedthatrollsbacktransactionsrelatedtoeachalreadyprocessedinputinstances.Insuch
situation,instancetransactionsaredistinctbutboundtogetherandthereforerolledbackasa
whole.

Unliketoreject,therejectMessageexceptionalwaysrejectstheinputmessage.Whenoccurring
inthestartevent,noinputdataisprocessed:controlisdirectlytransferredtotheendeventif
defined,ordirectlyfinishedotherwise.

Withmultiplesituationsandactions,thebehavioroftheengineisquitecomplextodescribe.The
followingdiagramtriestomakethingsclearer:

134Getting Started Guide Axway Mapping Services DML 3.0.1


How the system handles exceptions

Axway Mapping Services DML 3.0.1 Getting Started Guide135


10 Exceptions

Inthisdiagram,theprocessbeginsandendswiththedouble-circlestepsstart,message
acceptedandmessage rejected.Blueboxessymbolizetheexecutionofsub-networksofDML
Blocksthatarerelatedtoeventsordataprocessingmainstream.

Commitandrollbackactionsarepicturedwithgreenandbrowncircles;theyusuallyoperateonthe
currenttransaction,exceptforglobal rollbackthatcancelsallinstancetransactionswhenerror
recoveringisenabled.

Theemptybluecircleisthereforeaseofreading:itconcentratesseveralincomingpathsbeforethe
definitionoftheendeventisdetermined.

Exceptions and Custom Functions


YoucanraiseanexceptionnotonlyinalmostanyDMLexpressions,butalsoinCandJava-based
CustomFunctions.TodothisyouusethefunctionreturninClanguage,orbyraisinganexception
inJava.

WhenusingClanguage,asetofdefinesisprovidedthatrefertoeachexception:

XIBRT_SUCCESS noexceptionraised

XIBRT_SYSFATAL asystemerrorisdetected

XIBRT_REJECT_MESSAGErejectMessage exceptionraised

XIBRT_REJECT_INSTANCErejectInstance exceptionraised

ForCustomFunctionswrittenusingJavaprogramminglanguage,raisingtherejectMessage
exceptionisaccomplishedbythrowingaFunctionExceptionobjectwithitsinternalcodesetto
CUSTOM_EXCEPTION.

FoodBroker project: Handling absence of


partner rates
Inthepreviouschapter,youinsertedtheXMLfilethatcontainsthepartnerratesintoyourMapping
Flow.YouwroteaCustomFunctionthatloadsthefileintoaraw-data(classV)container,andthen
youusedthatCustomFunctioninconjunctionwithaspecialdecisionpathsteptoprovidetheMB_
extractorDMLBlockwiththeexpectedinformation.

WhencodingtheCustomFunctioninCprogramminglanguage,exceptionswerehandledusing
nullorabsentsymbolicforthereturnedvalues.Suchmanagementdoesnotdistinguishbetween
emptyornon-existentfilesandtechnicaldifficultiesinloadingapresentandfullfile.

136Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Handling absence of partner rates

Amoreaccurateprocesswould:
l Returnabsentwhenthesuppliedfiledoesnotexistorisempty
l Returnnullwhenthesuppliedfilenameisabsentornull
l Signalasystemerrorwhenthefunctionisnotabletoloadthefilefortechnicalreasons.
LetsreworkthecodeforLoadFile:

Axway Mapping Services DML 3.0.1 Getting Started Guide137


10 Exceptions

int LoadFile(EXE_HANDLE hCtx, EXE_hRegister hFileContents,


EXE_hRegister hFileName)
{
char szFileName[MAXPATH + 1];
FILE *pFile;
char *pBuffer;
size_t ulSize;

/* Reject calls with an empty filename */


if (xibrt_isNull(hCtx, hFilename) || xibrt_isNull(hCtx, hFilename))
{
xibrt_setNull(hCtx, hFileContents);
return XIBRT_SUCCESS;
}
/* Extract filename arguments
* The contents of hFileName is cloned into a static buffer
* theoricaly large enough to contain the whole filename.
* Only a loss of data is possible here (truncated filename)
* that occurs only when the filename is not
* filesystem compatible.
*/
xibrt_getString(hCtx, hFileName, sizeof(szFilename), szFilename);

/* Try to open the file and return absent on failure */


pFile = fopen(szFilename, "r");
if (!pFile)
{
if (errno != ENOENT)
{
return XIBRT_SYSFATAL;
}
xibrt_setAbsent(hCtx, hFileContents);
return XIBRT_SUCCESS;
}
/* Collect file size and allocate room for contents,
then load the file into the buffer and close it */
ulSize = fseek(pFile, 0, SEEK_END);
fseek(pFile, 0, SEEK_SET);
if (ulSize == 0)
{
xibrt_setAbsent(hCtx, hFileContents);
return XIBRT_SUCCESS;
}
pBuffer = (char *) malloc(ulSize);

138Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Handling absence of partner rates

if (!pBuffer)
{
return XIBRT_SYSFATAL;
}
ulSize = fread(pBuffer, 1, ulSize, pFile);
fclose(pFile);

/* Copy the file contents into the result blob */


xibrt_setBinary(hCtx, ulSize, pBuffer, hFileContents);

/* Perform some cleanup and return success */


free(pBuffer);
return XIBRT_SUCCESS;
}

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.

Axway Mapping Services DML 3.0.1 Getting Started Guide139


10 Exceptions

Thefollowinggraphicillustratesthisstrategy:

Tosilentlypropagatethedetectedproblem,youmustbeabletoprocesstheabsentvalueinboth
theMB_tableLoaderandMB_tableBuilderDMLBlocks.Intheformer,thevaluereturnedby
LoadFileisalwaysplacedintheoutputBusinessDocument,evenifthatvalueisabsent.Inthe
later,insteadofusingtheparsestep,anemptyoutputBusinessDocumentisgeneratedusinga
dedicatedMap.

TheMR_generateEmptyMapgeneratesaBusinessDocumentthathasonlyoneoccurrenceofthe
nodepartnerwhichgroupsbothnamesandratewithanabsentvalue.

140Getting Started Guide Axway Mapping Services DML 3.0.1


FoodBroker project: Handling absence of partner rates

Then,intheMB_extractorDMLBlock,thefirststepoftheDecision-Pathcheckswhetherthe
documentthatcomesfromratesisfullornot.Ifnot,anexitstepistriggeredthatraisesthe
rejectMessageexception:

TheexpressionboundtothefirstifstepinthisDecision-Pathistruewhenevernooccurrencesof
nodepartnerexistintheinputBusinessDocument,orwhenatleastoneofthenodesnameor
rateisfoundwithanabsentvalue.

Axway Mapping Services DML 3.0.1 Getting Started Guide141


10 Exceptions

142Getting Started Guide Axway Mapping Services DML 3.0.1


Appendices
11
ThischaptercontainsusefulinformationaboutDML,suchasrestrictionsontheuseofinstructions
andoperators,aquickreferenceofthelanguageandadditionalinformationabouttablesand
messagesattributes.

Use restrictions
AlthoughmostDMLinstructionsandoperatorscanbeusedinanyexpression,certainrestrictions
exist.ThefollowingtablesummarizeswhereyoucanuseDMLelementsandwhereyoucannot.

Instruction, statement Expression types


or operator
Check Variable Decision Mapping
Constraints initialization Paths Rules

literals

variablereading

variableassignment

explicitvalueassignmentusing$

+,-,*,/and**onnumbers

+and*onstrings

nodepaths

=, <>, <, <=, > and >= operators

and,or,xorandnot

ifthenelsestatement

switchstatement

definedandundefinedoperators

loop and whilestatements

Axway Mapping Services DML 3.0.1 Getting Started Guide143


11 Appendices

Instruction, statement Expression types


or operator
break
and next
instruction
s

loop onstatement

times and timesdo statements

for each and for eachdo

select statement

tree statement

exit statement

Quick-Reference
ReferenceinformationaboutDMLlanguageyoufindintheDMLReferenceGuide.

Defining and reading tables


Youmightneedextrainformationtop rocessyourinputdataandgeneratetheoutputs.Mostofthe
time,thisadditionalinformationisdefinedonlyonetimeandreadwhilegeneratingtheoutputs.

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.

144Getting Started Guide Axway Mapping Services DML 3.0.1


Defining and reading tables

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:

1. IntheProjectExplorerrightclickExtended Objects - TablesinyourprojectandselectNew


-> Table.

Axway Mapping Services DML 3.0.1 Getting Started Guide145


11 Appendices

2. WhenyouselecttheTable command,awizardforcreatinganewtableobjectopens.Typein
thenameforthenewtable.ClickonFinish tocreatethetable.TheTableeditoropens:

3. IntheTable DetailssectionyoucandefineaStart Date,anEnd Dateandyoucanselector


deselecttheoptionSend table contents to the server.
4. IntheTable Contentsectionyoucanaddcolumnsusingthecontextmenuonthelistheader:

5. WhenyouclickInsert a column before this column,theColumn propertieswindow


opens.Hereyoudefinethenewcolumn.

UsetheNamefieldtosetthenameofthecolumnandtheLabelfieldtodefineanoptional
detaileddescriptionofthecolumncontents.Youmustselecttheclassforthevalueofthe
column.Ifyouwanttodefinetocolumnasakey,justselecttheKey Columncheck-box.
6. Toaddlines(orrows)inthenewtable,clickthefirstbutton(greenplus)ofthetoolbaratthe
rightsideofthelistview.

146Getting Started Guide Axway Mapping Services DML 3.0.1


Defining and reading tables

Anewlineinthemainframeappears.Inthisnewlineyoucanenterthevaluesofeachcolumn.
ThetabledefinedaboveisasubstitutetotheXMLfileforpartnerratesinthisFoodBroker
example.Eachrowrelatestherate(Rate)forapartnerwithitsname(Name).
7. Checkandsavetheobject.
ThecolumnsandlinesthatyoudefinedinAxwayMappingServicesareimmutableduringdata
generation.IfyouneedtoalteratableyouhavetouseAxwayMappingServices.DMLisreservedfor
tablereading .InDML,youhavefunctionstocheckwhetheratleastonelineexistsinagiventable
thatmatchesasetofkeys.Hereisanexample:

if isKeyPresent(entity.folder1.TBL_PartnerRates, "Jaleo") then


{
addTrace("INFO", "Jaleo partner exists in the table")
}

ThefewlinesabovecheckwhetheralineexistsfortheJaleo partner.ThefunctionIsKeyPresent
returnstrueifsucharowexistsandfalseotherwise.TheveryfistargumentofIsKeyPresentis
thenameofthetableandcanbefullyqualifiedorabbreviated.Theremainingargumentsarethe
valuesforthekeysfollowingtheorderdefinedinAxwayMappingServices. Considerthefollowing
tabledefinedinAxwayMappingServices:

Tocheckwhetherarowexistsinthistable,yourcallstoIsKeyPresentmustcontainreal
argumentsforeachofthethreedefinedkeys:

if isKeyPresent(TBL_example, "K1", "K2", "K3") then


{
addTrace("INFO", "this is line 2")
}

CallstoisKeyPresentignoreStart DateandEnd Datecolumns.Toselectrowsthatmatcha


certaindate,youmustuseisKeyPresentInPeriodinstead.Thefollowingexpression:

%has_rate := isKeyPresentInPeriod(TBL_PartnerRates,
"Bombay Club Restaurant",
'2007-10-9')

setsthevariablehas_ratetotruebecausetheperiodbetweenStartDateandEndDateofthe1 st
lineofTBL_PartnerRatescontainsOct 9 th, 2007.

Axway Mapping Services DML 3.0.1 Getting Started Guide147


11 Appendices

YoucanalsoextractvaluesfromatableusingcallstoreturnColumn asfollows:

%rate := returnColumn(TBL_PartnerRates, "Old Ebbit Grill",


Rate)

AsforisKeyPresent,argumentsarethenameofthetablefollowedbythekeyvalues.Then,when
yourtablecontainsmorethanonevaluecolumn,youmustappendthenameoftheonethatyou
want.

WhenacalltoreturnColumnisevaluated,theintegrationenginegoesthroughthespecifiedtable
tofindthefirstrowwhichmatchesthespecifiedkeys.Ifnomatchisfound,thecallisevaluatedto
absent.

SelectionwithStart DateandEnd DatecanbedonewithreturnColumnInPeriodaschecking


withdateswasdonewithisKeyPresent.

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:

Attribute name Value Description


class

Use_Host I UsethecontentsofHostattribute

Host S RemotehostIPorDNSaddress

Use_Port I UsethecontentsofPortattribute

Port S RemoteFTPport

Use_User I UsethecontentsofUserattribute

User S Remoteusername

148Getting Started Guide Axway Mapping Services DML 3.0.1


Message attributes

Attribute name Value Description


class

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:

DECLARE PUBLIC RECORD foo


{
DECLARE PUBLIC FIELD $bar STRING;
}

Thisexampledefinesamessageattributenamedfoowithafieldnamedbar.Thisfieldholdsa
string.

Axway Mapping Services DML 3.0.1 Getting Started Guide149


11 Appendices

Working with attributes globally


Afteritisdefined,youcangetandsetmessageattributesvaluesusingcallstobuilt-infunctions.

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.

150Getting Started Guide Axway Mapping Services DML 3.0.1


Message attributes

Working with attributes on document


instances
Asstatedintheprevioussection,attributesarebasicallyattachedtoactivitymessages.Thismeans
theuseofset/getfunctionsreadandchangethevaluesglobally.Suchabehaviorisenoughfor
simpleMappingFlows.

MorecomplexMappingFlowsmightrequiretoreadortochangeattributevaluesattheBusiness
Documentinstancelevel.AtypicalsituationofthisisaMappingFlowthatmanagesasinglemessage
withmultipleinstancesofaBusinessDocumentinside.

Inthediagramabove,theidentifierofeachinvoiceiscomputedbytheDMLBlocksoftheMapping
Flow.ThatidiscarriedbyanattributenamedinvoiceIdwhichistransferredtoindividualoutput
messages.TocreateaMappingFlowwithsuchabehavior,attributesmustbemanagedatdocument
instancelevel.

Theintegrationengineofferstwobuilt-infunctionstosettheattributesatdocumentinstancelevel.

ThesearesetDocumentAttributeandsetDocumentAttributeToOutput.Theformercannotbe
usedoutsideaMapandaddressestheoutputdocumentofthatrule.Thelatercanbeusedin
decisionpathsonlyandaddressesthedocumentcarriedbytheoutputwhosenameisspecifiedas
anargument.

Axway Mapping Services DML 3.0.1 Getting Started Guide151


11 Appendices

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.

152Getting Started Guide Axway Mapping Services DML 3.0.1


Index

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

Axway Mapping Services DML 3.0.1 Getting Started Guide153


Index

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

154Getting Started Guide Axway Mapping Services DML 3.0.1


Index

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

Axway Mapping Services DML 3.0.1 Getting Started Guide155


Index

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

156Getting Started Guide Axway Mapping Services DML 3.0.1

You might also like