jptree.cpp 278 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include <unordered_map>
  14. #include <unordered_set>
  15. #include <string>
  16. #include "platform.h"
  17. #include "jarray.hpp"
  18. #include "jdebug.hpp"
  19. #include "jhash.hpp"
  20. #include "jmutex.hpp"
  21. #include "jexcept.hpp"
  22. #include "jlzw.hpp"
  23. #include "jregexp.hpp"
  24. #include "jstring.hpp"
  25. #include "jutil.hpp"
  26. #include "jmisc.hpp"
  27. #include "yaml.h"
  28. #include <initializer_list>
  29. #define MAKE_LSTRING(name,src,length) \
  30. const char *name = (const char *) alloca((length)+1); \
  31. memcpy((char *) name, (src), (length)); \
  32. *(char *) (name+(length)) = '\0';
  33. #include "jfile.hpp"
  34. #include "jlog.hpp"
  35. #include "jptree.ipp"
  36. #define WARNLEGACYCOMPARE
  37. #define XMLTAG_CONTENT "<>"
  38. #undef UNIMPLEMENTED
  39. #define UNIMPLEMENTED throw MakeIPTException(-1, "UNIMPLEMENTED")
  40. #define CHECK_ATTRIBUTE(X) if (X && isAttribute(X)) throw MakeIPTException(PTreeExcpt_XPath_Unsupported, "Attribute usage invalid here");
  41. #define AMBIGUOUS_PATH(X,P) { StringBuffer buf; buf.append(X": ambiguous xpath \"").append(P).append("\""); throw MakeIPTException(PTreeExcpt_XPath_Ambiguity,"%s",buf.str()); }
  42. #define PTREE_COMPRESS_THRESHOLD (4*1024) // i.e. only use compress if > threshold
  43. #define PTREE_COMPRESS_BOTHER_PECENTAGE (80) // i.e. if it doesn't compress to <80 % of original size don't bother
  44. class NullPTreeIterator final : implements IPropertyTreeIterator
  45. {
  46. public:
  47. virtual ~NullPTreeIterator() {}
  48. virtual void Link() const override {}
  49. virtual bool Release() const override { return true; }
  50. // IPropertyTreeIterator
  51. virtual bool first() override { return false; }
  52. virtual bool next() override { return false; }
  53. virtual bool isValid() override { return false; }
  54. virtual IPropertyTree & query() override { throwUnexpected(); }
  55. } *nullPTreeIterator;
  56. IPropertyTreeIterator *createNullPTreeIterator() { return LINK(nullPTreeIterator); } // initialized in init mod below.
  57. //===================================================================
  58. #ifdef USE_READONLY_ATOMTABLE
  59. RONameTable *AttrStrUnionWithTable::roNameTable = nullptr;
  60. RONameTable *AttrStrUnionWithValueTable::roValueTable = nullptr;
  61. #endif
  62. static AtomRefTable *keyTable = nullptr;
  63. static AtomRefTable *keyTableNC = nullptr;
  64. static CriticalSection hashcrit;
  65. static CAttrValHashTable *attrHT = nullptr;
  66. static AttrValue **freelist = nullptr;
  67. static unsigned freelistmax = 0;
  68. static CLargeMemoryAllocator freeallocator((memsize_t)-1, 0x1000*sizeof(AttrValue), true);
  69. #ifdef USE_READONLY_ATOMTABLE
  70. static const char * roAttributes[] =
  71. {
  72. #include "jptree-attrs.hpp" // potentially auto-generated
  73. nullptr
  74. };
  75. static const char * roAttributeValues[] =
  76. {
  77. #include "jptree-attrvalues.hpp" // potentially auto-generated
  78. nullptr
  79. };
  80. void initializeRoTable()
  81. {
  82. for (const char **attr = roAttributes; *attr; attr++)
  83. {
  84. AttrStrUnionWithTable::roNameTable->find(*attr, true);
  85. }
  86. for (const char **value = roAttributeValues; *value; value++)
  87. {
  88. AttrStrUnionWithValueTable::roValueTable->find(*value, true);
  89. }
  90. // also populate read-only value table by generating some common constants
  91. StringBuffer constStr;
  92. for (unsigned c=0; c<1000; c++) // common unsigned values in attributes
  93. {
  94. constStr.clear().append(c);
  95. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  96. }
  97. for (unsigned c=1; c<=400; c++) // outer graphs
  98. {
  99. constStr.clear().append("graph").append(c);
  100. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  101. constStr.clear().append("Graph graph ").append(c);
  102. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  103. }
  104. for (unsigned c=1; c<=200; c++) // subgraphs
  105. {
  106. constStr.clear().append("sg").append(c);
  107. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  108. }
  109. for (unsigned c=1; c<=200; c++) // Edge 0
  110. {
  111. constStr.clear().append(c).append("_0");
  112. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  113. }
  114. for (unsigned c=0; c<35; c++)
  115. {
  116. char ch = c<9 ? ('1' + c) : ('A' + (c-9));
  117. constStr.clear().append("~spill::").append(ch); // spills
  118. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  119. constStr.clear().append("gl").append(ch); // graph results
  120. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  121. constStr.clear().append("mf").append(ch); // meta factories
  122. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  123. }
  124. for (unsigned c=1; c<=10; c++) // global auto attributes
  125. {
  126. constStr.clear().append("auto").append(c);
  127. AttrStrUnionWithValueTable::roValueTable->find(constStr.str(), true);
  128. }
  129. #ifdef TRACE_ATOM_SIZE
  130. // If you are wanting an idea of the savings from use of the RO hash table, it may be useful to reset
  131. // the counts here. But it's more correct to actually leave them in place.
  132. //AttrStrAtom::totsize = 0;
  133. //AttrStrAtom::maxsize = 0;
  134. #endif
  135. #ifdef _DEBUG
  136. for (const char **a = roAttributes; *a; a++)
  137. {
  138. // sanity check
  139. unsigned idx = AttrStrUnionWithTable::roNameTable->findIndex(*a, AttrStrC::getHash(*a));
  140. AttrStrC *val = AttrStrUnionWithTable::roNameTable->getIndex(idx);
  141. assert(val && val->eq(*a));
  142. }
  143. for (const char **v = roAttributeValues; *v; v++)
  144. {
  145. // sanity check
  146. unsigned idx = AttrStrUnionWithValueTable::roValueTable->findIndex(*v, AttrStrC::getHash(*v));
  147. AttrStrC *val = AttrStrUnionWithValueTable::roValueTable->getIndex(idx);
  148. assert(val && val->eq(*v));
  149. }
  150. #endif
  151. }
  152. #endif
  153. MODULE_INIT(INIT_PRIORITY_JPTREE)
  154. {
  155. nullPTreeIterator = new NullPTreeIterator;
  156. #ifdef USE_READONLY_ATOMTABLE
  157. AttrStrUnionWithTable::roNameTable = new RONameTable(255);
  158. AttrStrUnionWithValueTable::roValueTable = new RONameTable(4095);
  159. initializeRoTable();
  160. #endif
  161. keyTable = new AtomRefTable;
  162. keyTableNC = new AtomRefTable(true);
  163. attrHT = new CAttrValHashTable;
  164. return true;
  165. }
  166. MODULE_EXIT()
  167. {
  168. delete nullPTreeIterator;
  169. delete attrHT;
  170. keyTable->Release();
  171. keyTableNC->Release();
  172. #ifdef USE_READONLY_ATOMTABLE
  173. delete AttrStrUnionWithTable::roNameTable;
  174. delete AttrStrUnionWithValueTable::roValueTable;
  175. #endif
  176. free(freelist);
  177. freelist = NULL;
  178. }
  179. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  180. {
  181. IPropertyTree *l = (IPropertyTree *) *ll;
  182. IPropertyTree *r = (IPropertyTree *) *rr;
  183. return stricmp(l->queryName(), r->queryName());
  184. };
  185. class CPTArrayIterator : public ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>
  186. {
  187. IArrayOf<IPropertyTree> elems;
  188. public:
  189. CPTArrayIterator(IPropertyTreeIterator &iter, TreeCompareFunc compare) : ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>(elems)
  190. {
  191. ForEach(iter)
  192. elems.append(iter.get());
  193. elems.sort(compare);
  194. }
  195. };
  196. IPropertyTreeIterator * createSortedIterator(IPropertyTreeIterator & iter)
  197. {
  198. return new CPTArrayIterator(iter, comparePropTrees);
  199. }
  200. IPropertyTreeIterator * createSortedIterator(IPropertyTreeIterator & iter, TreeCompareFunc compare)
  201. {
  202. return new CPTArrayIterator(iter, compare);
  203. }
  204. //////////////////
  205. unsigned ChildMap::getHashFromElement(const void *e) const
  206. {
  207. PTree &elem = (PTree &) (*(IPropertyTree *)e);
  208. return elem.queryHash();
  209. }
  210. unsigned ChildMap::numChildren()
  211. {
  212. SuperHashIteratorOf<IPropertyTree> iter(*this);
  213. if (!iter.first()) return 0;
  214. unsigned count = 0;
  215. do
  216. {
  217. PTree *element = (PTree *) &iter.query();
  218. if (element->value && element->value->isArray())
  219. count += element->value->elements();
  220. else
  221. ++count;
  222. }
  223. while (iter.next());
  224. return count;
  225. }
  226. IPropertyTreeIterator *ChildMap::getIterator(bool sort)
  227. {
  228. class CPTHashIterator : implements IPropertyTreeIterator, public CInterface
  229. {
  230. SuperHashIteratorOf<IPropertyTree> *hiter;
  231. public:
  232. IMPLEMENT_IINTERFACE;
  233. CPTHashIterator(SuperHashTable &table) { hiter = new SuperHashIteratorOf<IPropertyTree>(table); }
  234. ~CPTHashIterator() { hiter->Release(); }
  235. // IPropertyTreeIterator
  236. virtual bool first() override { return hiter->first(); }
  237. virtual bool next() override { return hiter->next(); }
  238. virtual bool isValid() override { return hiter->isValid(); }
  239. virtual IPropertyTree & query() override { return hiter->query(); }
  240. };
  241. Owned<IPropertyTreeIterator> baseIter = new CPTHashIterator(*this);
  242. if (!sort)
  243. return baseIter.getClear();
  244. return createSortedIterator(*baseIter);
  245. }
  246. ///////////
  247. bool validateXMLTag(const char *name)
  248. {
  249. if (!isValidXPathStartChr(*name)) return false;
  250. ++name;
  251. while (*name != '\0')
  252. {
  253. if (!isValidXPathChr(*name)) return false;
  254. ++name;
  255. }
  256. return true;
  257. }
  258. class jlib_thrown_decl CPTreeException : implements IPTreeException, public CInterface
  259. {
  260. int errCode;
  261. StringBuffer errMsg;
  262. public:
  263. IMPLEMENT_IINTERFACE;
  264. CPTreeException(int _errCode, const char *_errMsg, va_list &args) __attribute__((format(printf,3,0))) : errCode(_errCode)
  265. {
  266. if (_errMsg)
  267. errMsg.valist_appendf(_errMsg, args);
  268. }
  269. StringBuffer &translateCode(StringBuffer &out) const
  270. {
  271. out.append("IPropertyTree: ");
  272. switch (errCode)
  273. {
  274. case PTreeExcpt_XPath_Ambiguity:
  275. return out.append("Ambiguous xpath used");
  276. case PTreeExcpt_XPath_ParseError:
  277. return out.append("xpath parse error");
  278. case PTreeExcpt_XPath_Unsupported:
  279. return out.append("unsupported xpath syntax used");
  280. case PTreeExcpt_InvalidTagName:
  281. return out.append("Invalid tag name");
  282. default:
  283. return out.append("UNKNOWN ERROR CODE: ").append(errCode);
  284. }
  285. }
  286. // IException
  287. int errorCode() const { return errCode; }
  288. StringBuffer &errorMessage(StringBuffer &out) const
  289. {
  290. return translateCode(out).append("\n").append(errMsg.str());
  291. }
  292. MessageAudience errorAudience() const { return MSGAUD_user; }
  293. };
  294. static IPTreeException *MakeIPTException(int code, const char *format, ...) __attribute__((format(printf,2,3)));
  295. static IPTreeException *MakeXPathException(const char *xpath, int code, size_t pos, const char *format, ...) __attribute__((format(printf,4,5)));
  296. IPTreeException *MakeIPTException(int code, const char *format, ...)
  297. {
  298. va_list args;
  299. va_start(args, format);
  300. IPTreeException *e = new CPTreeException(code, format, args);
  301. va_end(args);
  302. return e;
  303. }
  304. IPTreeException *MakeXPathException(const char *xpath, int code, size_t pos, const char *format, ...)
  305. {
  306. va_list args;
  307. va_start(args, format);
  308. StringBuffer s("XPath Exception: ");
  309. s.valist_appendf(format, args);
  310. va_end(args);
  311. #ifdef _DEBUG
  312. PrintStackReport();
  313. #endif
  314. const char *msg = "in xpath = ";
  315. s.append("\n").append(msg).append(xpath);
  316. s.append("\n").appendN((size32_t)(strlen(msg)+pos), ' ').append("^");
  317. return MakeIPTException(code, "%s", s.str());
  318. }
  319. inline static void readID(const char *&xxpath, bool started)
  320. {
  321. const char *xpath = xxpath;
  322. if (isValidXPathStartChr(*xpath) || (started && isValidXPathChr(*xpath)))
  323. {
  324. do
  325. {
  326. xpath++;
  327. } while (isValidXPathChr(*xpath));
  328. xxpath = xpath;
  329. }
  330. }
  331. inline static void readWildId(const char *&xpath, bool &wild)
  332. {
  333. wild = false;
  334. for (;;)
  335. {
  336. readID(xpath, wild);
  337. if ('*' != *xpath)
  338. break;
  339. wild = true;
  340. ++xpath;
  341. }
  342. }
  343. inline const char * readIndex(const char *xpath, StringAttr &index)
  344. {
  345. const char *start = xpath;
  346. do { xpath++; } while (isdigit(*xpath));
  347. index.set(start, (xpath - start));
  348. return xpath;
  349. }
  350. inline static void readWildIdIndex(const char *&xpath, bool &wild, bool &numeric)
  351. {
  352. const char *_xpath = xpath;
  353. readWildId(xpath, wild);
  354. if ('[' == *xpath) // check for local index not iterative qualifier.
  355. {
  356. const char *end = xpath+1;
  357. if (isdigit(*end))
  358. {
  359. StringAttr index;
  360. end = readIndex(end, index);
  361. if (']' != *end)
  362. throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
  363. xpath = end+1;
  364. numeric = true;
  365. }
  366. else
  367. numeric = false;
  368. }
  369. else
  370. numeric = false;
  371. }
  372. inline static unsigned getTailIdLength(const char *xxpath, unsigned xxpathlength)
  373. {
  374. const char *xpath = xxpath+xxpathlength;
  375. const char *end = xpath;
  376. while (xpath != xxpath)
  377. {
  378. --xpath;
  379. if (!isValidXPathChr(*xpath)) break;
  380. }
  381. if (!isAttribute(xpath) && xpath != xxpath) ++xpath;
  382. return end-xpath;
  383. }
  384. const char *splitXPathUQ(const char *xpath, StringBuffer &path)
  385. {
  386. size32_t xpathSize = (size32_t) strlen(xpath);
  387. size32_t idSize = getTailIdLength(xpath, xpathSize);
  388. path.append(xpathSize-idSize, xpath);
  389. return xpath + (xpathSize-idSize);
  390. }
  391. const char *splitXPathX(const char *xpath)
  392. {
  393. size32_t xpathSize = (size32_t) strlen(xpath);
  394. size32_t idSize = getTailIdLength(xpath, xpathSize);
  395. return xpath + (xpathSize-idSize);
  396. }
  397. // similar to above, splitXPathUQ doesn't split if qualified
  398. const char *splitXPath(const char *xpath, StringBuffer &headPath)
  399. {
  400. StringBuffer path;
  401. const char *end = xpath+strlen(xpath);
  402. const char *prop = end;
  403. bool quote = false;
  404. bool braced = false;
  405. while (xpath != prop)
  406. {
  407. --prop;
  408. if (*prop == '"')
  409. {
  410. if (quote) quote = false;
  411. else quote = true;
  412. }
  413. else if (*prop == ']' && !quote)
  414. {
  415. assertex(!braced);
  416. braced = true;
  417. }
  418. else if (*prop == '[' && !quote)
  419. {
  420. assertex(braced);
  421. braced = false;
  422. }
  423. else if (*prop == '/' && !quote && !braced)
  424. {
  425. ++prop;
  426. break;
  427. }
  428. }
  429. if (prop == end)
  430. return NULL;
  431. else if (xpath != prop)
  432. {
  433. size32_t ps = prop-xpath-1;
  434. headPath.append(ps, xpath);
  435. }
  436. return prop;
  437. }
  438. const char *queryNextUnquoted(const char *str, char c)
  439. {
  440. bool quote = false;
  441. for (;;)
  442. {
  443. char next = *str;
  444. if (next == '\0')
  445. return NULL;
  446. if ('"' == next)
  447. quote = !quote;
  448. else if (c == next && !quote)
  449. return str;
  450. ++str;
  451. }
  452. }
  453. const char *queryHead(const char *xpath, StringBuffer &head)
  454. {
  455. if (!xpath) return NULL;
  456. const char *start = xpath;
  457. bool quote = false;
  458. bool braced = false;
  459. for (;;)
  460. {
  461. if (*xpath == '\0')
  462. return NULL;
  463. ++xpath;
  464. char next = *xpath;
  465. if ('"' == next)
  466. quote = !quote;
  467. else if (next == ']' && !quote)
  468. {
  469. assertex(braced);
  470. braced = false;
  471. }
  472. else if (next == '[' && !quote)
  473. {
  474. assertex(!braced);
  475. braced = true;
  476. }
  477. else if (next == '/' && !quote && !braced)
  478. {
  479. if ('/' == *start) // so leading '//'
  480. return start;
  481. else if ('/' == *(xpath+1)) // in middle of path
  482. {
  483. head.append(xpath-start, start);
  484. return xpath;
  485. }
  486. break;
  487. }
  488. }
  489. head.append(xpath-start, start);
  490. return xpath+1;
  491. }
  492. ///////////////////
  493. static constexpr unsigned defaultSiblingMapThreshold = 100;
  494. static unsigned siblingMapThreshold = (unsigned)-1; // off until configuration default it on.
  495. void setPTreeMappingThreshold(unsigned threshold)
  496. {
  497. /*
  498. * NB: setPTreeMappingThreshold() will automatically be called via loadConfiguration
  499. * Redefining this limit, will not effect existing maps, and should generally only be called once during startup.
  500. */
  501. if (0 == threshold)
  502. threshold = (unsigned)-1;
  503. siblingMapThreshold = threshold;
  504. }
  505. class CValueMap : public std::unordered_multimap<std::string, const IPropertyTree *>
  506. {
  507. public:
  508. CValueMap(const char *_lhs, IPTArrayValue &array)
  509. {
  510. IPropertyTree **elements = array.getRawArray();
  511. IPropertyTree **last = elements+array.elements();
  512. dbgassertex(elements != last);
  513. while (true)
  514. {
  515. const char *v = (*elements)->queryProp(_lhs);
  516. if (v)
  517. emplace(std::make_pair(std::string(v), *elements));
  518. elements++;
  519. if (last == elements)
  520. break;
  521. }
  522. }
  523. std::pair<CValueMap::iterator, CValueMap::iterator> find(const char *rhs)
  524. {
  525. return equal_range(std::string(rhs));
  526. }
  527. void insertEntry(const char *v, const IPropertyTree *tree)
  528. {
  529. emplace(std::make_pair(std::string(v), tree));
  530. }
  531. bool removeEntry(const char *v, const IPropertyTree *tree)
  532. {
  533. auto range = equal_range(std::string(v));
  534. if (range.first == range.second)
  535. return false;
  536. auto it = range.first;
  537. while (true)
  538. {
  539. if (it->second == tree)
  540. {
  541. it = erase(it);
  542. return true;
  543. }
  544. ++it;
  545. if (it == range.second)
  546. break;
  547. }
  548. throwUnexpected();
  549. }
  550. void replaceEntry(const char *oldV, const char *newV, const IPropertyTree *tree)
  551. {
  552. verifyex(removeEntry(oldV, tree));
  553. if (newV)
  554. insertEntry(newV, tree);
  555. }
  556. };
  557. class CQualifierMap
  558. {
  559. std::unordered_map<std::string, CValueMap *> attrValueMaps;
  560. CriticalSection crit;
  561. public:
  562. CQualifierMap()
  563. {
  564. }
  565. ~CQualifierMap()
  566. {
  567. for (auto &e: attrValueMaps)
  568. delete e.second;
  569. }
  570. CValueMap *addMapping(const char *lhs, IPTArrayValue &array)
  571. {
  572. CValueMap *valueMap = new CValueMap(lhs, array);
  573. attrValueMaps.emplace(std::make_pair(std::string(lhs), valueMap));
  574. return valueMap;
  575. }
  576. CValueMap *addMappingIfNew(const char *lhs, IPTArrayValue &array)
  577. {
  578. CriticalBlock b(crit);
  579. auto it = attrValueMaps.find(lhs);
  580. if (it == attrValueMaps.end())
  581. return addMapping(lhs, array);
  582. else
  583. return it->second;
  584. }
  585. void addMatchingValues(const IPropertyTree *tree)
  586. {
  587. for (auto &e: attrValueMaps)
  588. {
  589. const char *v = tree->queryProp(e.first.c_str());
  590. if (v)
  591. e.second->insertEntry(v, tree);
  592. }
  593. }
  594. void removeMatchingValues(const IPropertyTree *tree)
  595. {
  596. for (auto &e: attrValueMaps)
  597. {
  598. const char *lhsp = e.first.c_str();
  599. const char *oldV = tree->queryProp(lhsp);
  600. if (oldV)
  601. verifyex(e.second->removeEntry(oldV, tree));
  602. }
  603. }
  604. void replaceMatchingValues(const IPropertyTree *oldTree, const IPropertyTree *newTree)
  605. {
  606. for (auto &e: attrValueMaps)
  607. {
  608. const char *lhsp = e.first.c_str();
  609. const char *oldV = oldTree->queryProp(lhsp);
  610. if (oldV)
  611. {
  612. verifyex(e.second->removeEntry(oldV, oldTree));
  613. const char *newV = newTree->queryProp(lhsp);
  614. if (newV)
  615. e.second->insertEntry(newV, newTree);
  616. }
  617. }
  618. }
  619. CValueMap *find(const char *lhs)
  620. {
  621. auto it = attrValueMaps.find(lhs);
  622. if (it == attrValueMaps.end())
  623. return nullptr;
  624. return it->second;
  625. }
  626. void removeEntryIfMapped(const char *lhs, const char *v, const IPropertyTree *tree)
  627. {
  628. auto it = attrValueMaps.find(lhs);
  629. if (it != attrValueMaps.end())
  630. it->second->removeEntry(v, tree);
  631. }
  632. void insertEntryIfMapped(const char *lhs, const char *v, const IPropertyTree *tree)
  633. {
  634. auto it = attrValueMaps.find(lhs);
  635. if (it != attrValueMaps.end())
  636. it->second->insertEntry(v, tree);
  637. }
  638. void replaceEntryIfMapped(const char *lhs, const char *oldv, const char *newv, const IPropertyTree *tree)
  639. {
  640. auto it = attrValueMaps.find(lhs);
  641. if (it != attrValueMaps.end())
  642. it->second->replaceEntry(oldv, newv, tree);
  643. }
  644. };
  645. // parse qualifier, returns true if simple equality expression found
  646. static bool parseEqualityQualifier(const char *&xxpath, unsigned &lhsLen, const char *&rhsBegin, unsigned &rhsLen)
  647. {
  648. const char *xpath = xxpath;
  649. while (*xpath == ' ' || *xpath == '\t') xpath++;
  650. if ('@' != *xpath) // only attributes supported
  651. return false;
  652. const char *start = xpath;
  653. char quote = 0;
  654. const char *lhsEnd, *quoteBegin, *quoteEnd, *rhsEnd;
  655. lhsEnd = quoteBegin = quoteEnd = rhsBegin = rhsEnd = NULL;
  656. bool equalSignFound = false;
  657. for (;;)
  658. {
  659. switch (*xpath)
  660. {
  661. case '"':
  662. case '\'':
  663. if (quote)
  664. {
  665. if (*xpath == quote)
  666. {
  667. quote = 0;
  668. quoteEnd = xpath;
  669. }
  670. }
  671. else
  672. {
  673. if (quoteBegin)
  674. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Quoted left hand side already seen");
  675. quote = *xpath;
  676. quoteBegin = xpath+1;
  677. }
  678. break;
  679. case '[':
  680. if (!quote)
  681. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unclosed qualifier detected");
  682. break;
  683. case ']':
  684. if (!quote)
  685. {
  686. if (!lhsEnd)
  687. lhsEnd = xpath;
  688. rhsEnd = xpath;
  689. }
  690. break;
  691. case ' ':
  692. case '\t':
  693. if (!lhsEnd)
  694. lhsEnd = xpath;
  695. break;
  696. case '!':
  697. case '>':
  698. case '<':
  699. case '~':
  700. case '/':
  701. if (!quote)
  702. return false;
  703. break;
  704. case '=':
  705. if (!quote)
  706. {
  707. if (equalSignFound)
  708. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator xpath");
  709. equalSignFound = true;
  710. if (!lhsEnd)
  711. lhsEnd = xpath;
  712. }
  713. break;
  714. case '?':
  715. case '*':
  716. return false;
  717. case '\0':
  718. rhsEnd = xpath;
  719. break;
  720. }
  721. if (rhsEnd)
  722. break;
  723. xpath++;
  724. if (!rhsBegin && equalSignFound && !isspace(*xpath))
  725. rhsBegin = xpath;
  726. }
  727. if (quote)
  728. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, unclosed quoted content");
  729. if (!equalSignFound)
  730. return false;
  731. lhsLen = lhsEnd-start;
  732. if (quoteBegin && !quoteEnd)
  733. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, RHS missing closing quote");
  734. if (rhsBegin && !rhsEnd)
  735. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, RHS missing closing quote");
  736. if (!quoteBegin && rhsEnd) // only if numeric
  737. return false;
  738. else // quoted
  739. {
  740. rhsBegin = quoteBegin;
  741. rhsLen = quoteEnd - rhsBegin;
  742. }
  743. if (rhsEnd && *xpath == ']')
  744. xpath++;
  745. xxpath = xpath;
  746. return true;
  747. }
  748. class CMapQualifierIterator : public CInterfaceOf<IPropertyTreeIterator>
  749. {
  750. CValueMap::iterator startRange, endRange;
  751. CValueMap::iterator currentIter;
  752. public:
  753. CMapQualifierIterator(CQualifierMap &_map, CValueMap::iterator _startRange, CValueMap::iterator _endRange)
  754. : startRange(_startRange), endRange(_endRange)
  755. {
  756. }
  757. // IPropertyTreeIterator
  758. virtual bool first() override
  759. {
  760. currentIter = startRange;
  761. return currentIter != endRange;
  762. }
  763. virtual bool next() override
  764. {
  765. currentIter++;
  766. return currentIter != endRange;
  767. }
  768. virtual bool isValid() override
  769. {
  770. return currentIter != endRange;
  771. }
  772. virtual IPropertyTree & query() override { return const_cast<IPropertyTree &>(*currentIter->second); }
  773. };
  774. IPropertyTreeIterator *checkMapIterator(const char *&xxpath, IPropertyTree &child)
  775. {
  776. /*
  777. * NB: IPT's are not thread safe. It is up to the caller to ensure multiple writers do not contend.
  778. * ( Dali for example ensures writer threads are exclusive )
  779. *
  780. * That means multiple reader threads could be here concurrently.
  781. * >1 could be constructing the qualifier map for the 1st time.
  782. * For new attr updates (where map already exists), it will block on map::crit,
  783. * so that there is at most 1 thread updating the map. The underlying unordered_multiset
  784. * is thread safe if 1 writer, and multiple readers.
  785. *
  786. * On initial map creation, allow concurrency, but only 1 will succeed to swap in the new active map.
  787. * That could mean a new attr/prop. mapping is lost, until next used.
  788. * NB: once the map is live, updates are write ops. and so, just as with the IPT
  789. * itself, it is expected that something will keep it thread safe (as Dali does)
  790. *
  791. */
  792. // NB: only support simple @<attrname>=<value> qualifiers
  793. if (((unsigned)-1) == siblingMapThreshold) // disabled
  794. return nullptr;
  795. PTree &_child = (PTree &)child;
  796. if (child.isCaseInsensitive()) // NB: could support but not worth it.
  797. return nullptr;
  798. IPTArrayValue *value = _child.queryValue();
  799. if (!value)
  800. return nullptr;
  801. CQualifierMap *map = value->queryMap();
  802. if (!map)
  803. {
  804. if (!value->isArray() || (value->elements() < siblingMapThreshold))
  805. return nullptr;
  806. }
  807. unsigned lhsLen, rhsLen;
  808. const char *rhsStart;
  809. const char *xpath = xxpath;
  810. if (!parseEqualityQualifier(xpath, lhsLen, rhsStart, rhsLen))
  811. return nullptr;
  812. MAKE_LSTRING(lhs, xxpath, lhsLen);
  813. MAKE_LSTRING(rhs, rhsStart, rhsLen);
  814. // NB: there can be a race here where >1 reader is constructing new map
  815. CValueMap *valueMap = nullptr;
  816. if (map)
  817. valueMap = map->addMappingIfNew(lhs, *value);
  818. else
  819. {
  820. OwnedPtr<CQualifierMap> newMap = new CQualifierMap();
  821. valueMap = newMap->addMapping(lhs, *value);
  822. /*
  823. * NB: it's possible another read thread got here 1st, and swapped in a map.
  824. * setMap returns the existing map, and the code below checks to see if it already
  825. * handles the 'lhs' we're adding, if it doesn't it re-adds the qualifier mappings.
  826. */
  827. map = value->setMap(newMap);
  828. if (!map) // successfully swapped newMap in.
  829. map = newMap.getClear(); // NB: setMap owns
  830. else // another thread has swapped in a map whilst I was creating new one
  831. valueMap = map->addMappingIfNew(lhs, *value);
  832. }
  833. xxpath = xpath; // update parsed position
  834. auto range = valueMap->find(rhs);
  835. if (range.first != range.second)
  836. return new CMapQualifierIterator(*map, range.first, range.second);
  837. else
  838. return LINK(nullPTreeIterator);
  839. }
  840. ///////////////////
  841. class SeriesPTIterator : implements IPropertyTreeIterator, public CInterface
  842. {
  843. public:
  844. IMPLEMENT_IINTERFACE;
  845. SeriesPTIterator() : current(NULL), cp(0)
  846. {
  847. }
  848. void addIterator(IPropertyTreeIterator *iter) { iters.append(*iter); }
  849. // IPropertyTreeIterator impl.
  850. virtual bool first() override
  851. {
  852. cp = 0;
  853. iterCount = iters.ordinality();
  854. if (nextIterator())
  855. return true;
  856. else
  857. return false;
  858. }
  859. virtual bool next() override
  860. {
  861. while (currentIter)
  862. {
  863. if (currentIter->next())
  864. {
  865. current = &currentIter->query();
  866. return true;
  867. }
  868. if (nextIterator())
  869. return true;
  870. }
  871. current = NULL;
  872. return false;
  873. }
  874. virtual bool isValid() override { return (NULL != current); }
  875. virtual IPropertyTree & query() override { assertex(current); return *current; }
  876. private:
  877. bool nextIterator()
  878. {
  879. while (cp<iterCount)
  880. {
  881. currentIter = (IPropertyTreeIterator *) &iters.item(cp++);
  882. if (currentIter->first())
  883. {
  884. current = &currentIter->query();
  885. return true;
  886. }
  887. }
  888. current = NULL;
  889. currentIter = NULL;
  890. return false;
  891. }
  892. IArray iters;
  893. IPropertyTreeIterator *currentIter;
  894. IPropertyTree *current;
  895. unsigned cp, iterCount;
  896. };
  897. ///////////////////
  898. CPTValue::CPTValue(size32_t size, const void *data, bool binary, bool raw, bool _compressed)
  899. {
  900. compressed = _compressed;
  901. if (!raw && binary && size > PTREE_COMPRESS_THRESHOLD)
  902. {
  903. unsigned newSize = size * PTREE_COMPRESS_BOTHER_PECENTAGE / 100;
  904. void *newData = NULL;
  905. ICompressor *compressor = NULL;
  906. try
  907. {
  908. newData = malloc(sizeof(size32_t) + newSize);
  909. compressor = createLZWCompressor();
  910. compressor->open(((char *)newData) + sizeof(size32_t), newSize);
  911. if (compressor->write(data, size)==size)
  912. {
  913. compressor->close();
  914. memcpy(newData, &size, sizeof(size32_t));
  915. newSize = sizeof(size32_t) + compressor->buflen();
  916. compressed = true;
  917. set(newSize, newData);
  918. }
  919. free(newData);
  920. compressor->Release();
  921. }
  922. catch (...)
  923. {
  924. if (newData)
  925. free(newData);
  926. if (compressor) compressor->Release();
  927. throw;
  928. }
  929. }
  930. if (raw || !compressed)
  931. set(size, data);
  932. }
  933. static void *uncompress(const void *src, size32_t &sz)
  934. {
  935. IExpander *expander = NULL;
  936. void *uncompressedValue = NULL;
  937. try
  938. {
  939. memcpy(&sz, src, sizeof(size32_t));
  940. assertex(sz);
  941. expander = createLZWExpander();
  942. src = ((const char *)src) + sizeof(size32_t);
  943. uncompressedValue = malloc(sz);
  944. assertex(uncompressedValue);
  945. expander->init(src);
  946. expander->expand(uncompressedValue);
  947. expander->Release();
  948. return uncompressedValue;
  949. }
  950. catch (...)
  951. {
  952. if (expander) expander->Release();
  953. if (uncompressedValue) free(uncompressedValue);
  954. throw;
  955. }
  956. }
  957. const void *CPTValue::queryValue() const
  958. {
  959. if (compressed)
  960. {
  961. size32_t sz;
  962. void *uncompressedValue = uncompress(get(), sz);
  963. ((MemoryAttr *)this)->setOwn(sz, uncompressedValue);
  964. compressed = false;
  965. }
  966. return get();
  967. }
  968. void CPTValue::serialize(MemoryBuffer &tgt)
  969. {
  970. //Retain backward compatibility for the serialization format.
  971. size32_t serialLen = (size32_t)length();
  972. tgt.append(serialLen);
  973. if (serialLen)
  974. {
  975. tgt.append(compressed);
  976. tgt.append(serialLen, get());
  977. }
  978. }
  979. void CPTValue::deserialize(MemoryBuffer &src)
  980. {
  981. size32_t sz;
  982. src.read(sz);
  983. if (sz)
  984. {
  985. src.read(compressed);
  986. set(sz, src.readDirect(sz));
  987. }
  988. else
  989. {
  990. compressed = false;
  991. clear();
  992. }
  993. }
  994. MemoryBuffer &CPTValue::getValue(MemoryBuffer &tgt, bool binary) const
  995. {
  996. if (compressed)
  997. {
  998. size32_t sz;
  999. void *uncompressedValue = uncompress(get(), sz);
  1000. if (!binary) sz -= 1;
  1001. tgt.append(sz, uncompressedValue);
  1002. if (uncompressedValue)
  1003. free(uncompressedValue);
  1004. }
  1005. else
  1006. {
  1007. if (binary)
  1008. tgt.append((size32_t)length(), get());
  1009. else
  1010. tgt.append((size32_t)length()-1, get());
  1011. }
  1012. return tgt;
  1013. }
  1014. StringBuffer &CPTValue::getValue(StringBuffer &tgt, bool binary) const
  1015. {
  1016. if (compressed)
  1017. {
  1018. size32_t sz;
  1019. void *uncompressedValue = NULL;
  1020. try
  1021. {
  1022. uncompressedValue = uncompress(get(), sz);
  1023. if (!binary) sz -= 1;
  1024. tgt.append(sz, (const char *)uncompressedValue);
  1025. free(uncompressedValue);
  1026. }
  1027. catch (IException *)
  1028. {
  1029. if (uncompressedValue) free(uncompressedValue);
  1030. throw;
  1031. }
  1032. }
  1033. else
  1034. {
  1035. if (binary) // this should probably be an assert?
  1036. tgt.append((size32_t)length(), (const char *)get());
  1037. else if (length())
  1038. tgt.append((size32_t)length()-1, (const char *)get());
  1039. }
  1040. return tgt;
  1041. }
  1042. size32_t CPTValue::queryValueSize() const
  1043. {
  1044. if (compressed)
  1045. {
  1046. size32_t sz;
  1047. memcpy(&sz, get(), sizeof(size32_t));
  1048. return sz;
  1049. }
  1050. else
  1051. return (size32_t)length();
  1052. }
  1053. ///////////////////
  1054. CPTArray::~CPTArray()
  1055. {
  1056. if (map.load())
  1057. delete map.load();
  1058. }
  1059. CQualifierMap *CPTArray::setMap(CQualifierMap *_map)
  1060. {
  1061. CQualifierMap *expected = nullptr;
  1062. if (map.compare_exchange_strong(expected, _map))
  1063. return nullptr;
  1064. else
  1065. return expected;
  1066. }
  1067. void CPTArray::addElement(IPropertyTree *tree)
  1068. {
  1069. append(*tree);
  1070. CQualifierMap *map = queryMap();
  1071. if (map)
  1072. {
  1073. if (tree->getAttributeCount())
  1074. map->addMatchingValues(tree);
  1075. }
  1076. }
  1077. void CPTArray::setElement(unsigned idx, IPropertyTree *tree)
  1078. {
  1079. CQualifierMap *map = queryMap();
  1080. if (map)
  1081. {
  1082. // remove any mappings for existing element.
  1083. if (isItem(idx))
  1084. {
  1085. IPropertyTree *existing = &((IPropertyTree &)item(idx));
  1086. map->replaceMatchingValues(existing, tree);
  1087. }
  1088. else
  1089. map->addMatchingValues(tree);
  1090. }
  1091. add(*tree, idx);
  1092. }
  1093. void CPTArray::removeElement(unsigned idx)
  1094. {
  1095. CQualifierMap *map = queryMap();
  1096. if (map)
  1097. {
  1098. IPropertyTree *existing = &((IPropertyTree &)item(idx));
  1099. map->removeMatchingValues(existing);
  1100. }
  1101. remove(idx);
  1102. }
  1103. unsigned CPTArray::find(const IPropertyTree *search) const
  1104. {
  1105. IInterface **start = getArray();
  1106. IInterface **last = start + ordinality();
  1107. IInterface **members = start;
  1108. while (true)
  1109. {
  1110. if (*members == search)
  1111. return members-start;
  1112. members++;
  1113. if (members == last)
  1114. break;
  1115. }
  1116. return NotFound;
  1117. }
  1118. //////////////////
  1119. PTree::PTree(byte _flags, IPTArrayValue *_value, ChildMap *_children)
  1120. {
  1121. flags = _flags;
  1122. children = LINK(_children);
  1123. value = _value;
  1124. }
  1125. PTree::~PTree()
  1126. {
  1127. if (value) delete value;
  1128. ::Release(children);
  1129. }
  1130. IPropertyTree *PTree::queryChild(unsigned index)
  1131. {
  1132. if (!value) return NULL;
  1133. if (!value->isArray()) return this;
  1134. IPropertyTree *v = value->queryElement(index);
  1135. return v;
  1136. }
  1137. aindex_t PTree::findChild(IPropertyTree *child, bool remove)
  1138. {
  1139. if (value && value->isArray())
  1140. {
  1141. unsigned pos = value->find(child);
  1142. if (remove && NotFound != pos)
  1143. value->removeElement(pos);
  1144. return pos;
  1145. }
  1146. else if (checkChildren())
  1147. {
  1148. IPropertyTree *_child = children->query(child->queryName());
  1149. if (_child == child)
  1150. {
  1151. if (remove)
  1152. children->removeExact(_child);
  1153. return 0;
  1154. }
  1155. else if (_child)
  1156. {
  1157. PTree *__child = (PTree *) _child;
  1158. return __child->findChild(child, remove);
  1159. }
  1160. }
  1161. return NotFound;
  1162. }
  1163. ChildMap *PTree::checkChildren() const
  1164. {
  1165. return children;
  1166. }
  1167. void PTree::setLocal(size32_t l, const void *data, bool _binary)
  1168. {
  1169. if (value) delete value;
  1170. if (l)
  1171. value = new CPTValue(l, data, _binary);
  1172. else
  1173. value = NULL;
  1174. if (_binary)
  1175. IptFlagSet(flags, ipt_binary);
  1176. else
  1177. IptFlagClr(flags, ipt_binary);
  1178. }
  1179. void PTree::appendLocal(size32_t l, const void *data, bool binary)
  1180. {
  1181. if (0 == l) return;
  1182. MemoryBuffer mb;
  1183. if (value)
  1184. {
  1185. assertex(!value->isArray());
  1186. assertex(binary == IptFlagTst(flags, ipt_binary));
  1187. value->getValue(mb, binary);
  1188. mb.append(l, data);
  1189. delete value;
  1190. l = mb.length();
  1191. data = mb.toByteArray();
  1192. }
  1193. if (l)
  1194. value = new CPTValue(l, data, binary);
  1195. else
  1196. value = NULL;
  1197. if (binary)
  1198. IptFlagSet(flags, ipt_binary);
  1199. else
  1200. IptFlagClr(flags, ipt_binary);
  1201. }
  1202. // IPropertyTree impl.
  1203. bool PTree::hasProp(const char * xpath) const
  1204. {
  1205. const char *prop = splitXPathX(xpath);
  1206. if (isAttribute(prop)) // JCS - note no wildcards on attributes
  1207. {
  1208. if (prop != xpath)
  1209. {
  1210. MAKE_LSTRING(path, xpath, prop-xpath);
  1211. Owned<IPropertyTreeIterator> iter = getElements(path);
  1212. if (iter->first())
  1213. {
  1214. do
  1215. {
  1216. IPropertyTree &branch = iter->query();
  1217. if (branch.hasProp(prop))
  1218. return true;
  1219. }
  1220. while (iter->next());
  1221. }
  1222. return false;
  1223. }
  1224. else
  1225. return nullptr != findAttribute(xpath);
  1226. }
  1227. else
  1228. {
  1229. IPropertyTreeIterator *iter = getElements(xpath);
  1230. bool res = iter->first();
  1231. iter->Release();
  1232. return res;
  1233. }
  1234. }
  1235. const char *PTree::queryProp(const char *xpath) const
  1236. {
  1237. if (!xpath)
  1238. {
  1239. if (!value) return NULL;
  1240. return (const char *) value->queryValue();
  1241. }
  1242. else if (isAttribute(xpath))
  1243. return getAttributeValue(xpath);
  1244. else
  1245. {
  1246. const char *prop = splitXPathX(xpath);
  1247. if (isAttribute(prop))
  1248. {
  1249. MAKE_LSTRING(path, xpath, prop-xpath);
  1250. IPropertyTree *branch = queryPropTree(path);
  1251. if (!branch) return NULL;
  1252. return branch->queryProp(prop);
  1253. }
  1254. else
  1255. {
  1256. IPropertyTree *branch = queryPropTree(xpath);
  1257. if (!branch) return NULL;
  1258. return branch->queryProp(NULL);
  1259. }
  1260. }
  1261. }
  1262. bool PTree::getProp(const char *xpath, StringBuffer &ret) const
  1263. {
  1264. if (!xpath)
  1265. {
  1266. if (!value) return false;
  1267. value->getValue(ret, IptFlagTst(flags, ipt_binary));
  1268. return true;
  1269. }
  1270. else if (isAttribute(xpath))
  1271. {
  1272. const char *value = getAttributeValue(xpath);
  1273. if (!value) return false;
  1274. ret.append(value);
  1275. return true;
  1276. }
  1277. else
  1278. {
  1279. const char *prop = splitXPathX(xpath);
  1280. if (isAttribute(prop))
  1281. {
  1282. MAKE_LSTRING(path, xpath, prop-xpath)
  1283. IPropertyTree *branch = queryPropTree(path);
  1284. if (!branch) return false;
  1285. return branch->getProp(prop, ret);
  1286. }
  1287. else
  1288. {
  1289. IPropertyTree *branch = queryPropTree(xpath);
  1290. if (!branch) return false;
  1291. return branch->getProp(NULL, ret);
  1292. }
  1293. }
  1294. }
  1295. void PTree::setProp(const char *xpath, const char *val)
  1296. {
  1297. if (!xpath || '\0' == *xpath)
  1298. {
  1299. if (!val)
  1300. {
  1301. if (value) delete value;
  1302. value = NULL;
  1303. }
  1304. else
  1305. {
  1306. size32_t l=(size32_t)strlen(val);
  1307. if (!l)
  1308. {
  1309. if (value) delete value;
  1310. value = NULL;
  1311. }
  1312. else
  1313. setLocal(l+1, val);
  1314. }
  1315. }
  1316. else if (isAttribute(xpath))
  1317. {
  1318. if (!val)
  1319. removeAttribute(xpath);
  1320. else
  1321. setAttribute(xpath, val);
  1322. }
  1323. else
  1324. {
  1325. const char *prop;
  1326. IPropertyTree *branch = splitBranchProp(xpath, prop, true);
  1327. if (isAttribute(prop))
  1328. branch->setProp(prop, val);
  1329. else
  1330. {
  1331. if (val)
  1332. {
  1333. IPropertyTree *propBranch = queryCreateBranch(branch, prop);
  1334. propBranch->setProp(NULL, val);
  1335. }
  1336. else
  1337. branch->removeProp(prop);
  1338. }
  1339. }
  1340. }
  1341. aindex_t PTree::getChildMatchPos(const char *xpath)
  1342. {
  1343. Owned<IPropertyTreeIterator> childIter = getElements(xpath);
  1344. if (!childIter->first())
  1345. return (aindex_t)-1;
  1346. IPropertyTree &childMatch = childIter->query();
  1347. if (childIter->next())
  1348. AMBIGUOUS_PATH("addPropX", xpath);
  1349. if (value)
  1350. if (value->isArray())
  1351. return findChild(&childMatch);
  1352. else
  1353. return 0;
  1354. else
  1355. return 0;
  1356. }
  1357. void PTree::resolveParentChild(const char *xpath, IPropertyTree *&parent, IPropertyTree *&child, StringAttr &path, StringAttr &qualifier)
  1358. {
  1359. parent = child = NULL;
  1360. if (!xpath)
  1361. throw MakeIPTException(-1, "No path to resolve parent from");
  1362. const char *end = xpath+strlen(xpath);
  1363. const char *prop = end;
  1364. while (prop != xpath && *(prop-1) != '/')
  1365. --prop;
  1366. size32_t ps = prop-xpath;
  1367. if (ps)
  1368. {
  1369. path.set(xpath, ps);
  1370. Owned<IPropertyTreeIterator> pathIter = getElements(path);
  1371. if (!pathIter->first())
  1372. throw MakeIPTException(-1, "resolveParentChild: path not found %s", xpath);
  1373. /* If 'path' resolves to iterator of this, then treat as if no leading path
  1374. * i.e. "./x", or "././.x" is equivalent to "x"
  1375. */
  1376. if (this != &pathIter->query())
  1377. {
  1378. IPropertyTree *currentPath = NULL;
  1379. bool multiplePaths = false;
  1380. bool multipleChildMatches = false;
  1381. for (;;)
  1382. {
  1383. // JCSMORE - a bit annoying has to be done again once path has been established
  1384. currentPath = &pathIter->query();
  1385. Owned<IPropertyTreeIterator> childIter = currentPath->getElements(prop);
  1386. if (childIter->first())
  1387. {
  1388. child = &childIter->query();
  1389. if (parent)
  1390. AMBIGUOUS_PATH("resolveParentChild", xpath);
  1391. if (!multipleChildMatches && childIter->next())
  1392. multipleChildMatches = true;
  1393. parent = currentPath;
  1394. }
  1395. if (pathIter->next())
  1396. multiplePaths = true;
  1397. else break;
  1398. }
  1399. if (!parent)
  1400. {
  1401. if (multiplePaths) // i.e. no unique path to child found and multiple parent paths
  1402. AMBIGUOUS_PATH("resolveParentChild", xpath);
  1403. parent = currentPath;
  1404. }
  1405. if (multipleChildMatches)
  1406. child = NULL; // single parent, but no single child.
  1407. path.set(prop);
  1408. const char *pstart = prop;
  1409. bool wild;
  1410. readWildId(prop, wild);
  1411. size32_t s = prop-pstart;
  1412. if (wild)
  1413. throw MakeXPathException(pstart, PTreeExcpt_XPath_ParseError, s-1, "Wildcards not permitted on add");
  1414. assertex(s);
  1415. path.set(pstart, s);
  1416. qualifier.set(prop);
  1417. return;
  1418. }
  1419. }
  1420. assertex(prop && *prop);
  1421. parent = this;
  1422. const char *pstart = prop;
  1423. bool wild;
  1424. readWildId(prop, wild);
  1425. assertex(!wild);
  1426. size32_t s = prop-pstart;
  1427. if (*prop && *prop != '[')
  1428. throw MakeXPathException(pstart, PTreeExcpt_XPath_ParseError, s, "Qualifier expected e.g. [..]");
  1429. path.set(pstart, s);
  1430. if (checkChildren())
  1431. child = children->query(path);
  1432. if (child)
  1433. qualifier.set(prop);
  1434. else
  1435. qualifier.clear();
  1436. }
  1437. void PTree::addProp(const char *xpath, const char *val)
  1438. {
  1439. if (!xpath || '\0' == *xpath)
  1440. addLocal((size32_t)strlen(val)+1, val);
  1441. else if (isAttribute(xpath))
  1442. setAttribute(xpath, val);
  1443. else if ('[' == *xpath)
  1444. {
  1445. aindex_t pos = getChildMatchPos(xpath);
  1446. if ((aindex_t) -1 == pos)
  1447. throw MakeIPTException(-1, "addProp: qualifier unmatched %s", xpath);
  1448. addLocal((size32_t)strlen(val)+1, val, false, pos);
  1449. }
  1450. else
  1451. {
  1452. IPropertyTree *parent, *child;
  1453. StringAttr path, qualifier;
  1454. resolveParentChild(xpath, parent, child, path, qualifier);
  1455. if (parent != this)
  1456. parent->addProp(path, val);
  1457. else if (child)
  1458. child->addProp(qualifier, val);
  1459. else
  1460. setProp(path, val);
  1461. }
  1462. }
  1463. void PTree::appendProp(const char *xpath, const char *val)
  1464. {
  1465. if (!xpath || '\0' == *xpath)
  1466. appendLocal((size_t)strlen(val)+1, val, false);
  1467. else if (isAttribute(xpath))
  1468. {
  1469. StringBuffer newVal;
  1470. getProp(xpath, newVal);
  1471. newVal.append(val);
  1472. setAttribute(xpath, newVal.str());
  1473. }
  1474. else if ('[' == *xpath)
  1475. {
  1476. IPropertyTree *qualified = queryPropTree(xpath);
  1477. if (!qualified)
  1478. throw MakeIPTException(-1, "appendProp: qualifier unmatched %s", xpath);
  1479. qualified->appendProp(nullptr, val);
  1480. }
  1481. else
  1482. {
  1483. IPropertyTree *parent, *child;
  1484. StringAttr path, qualifier;
  1485. resolveParentChild(xpath, parent, child, path, qualifier);
  1486. if (parent != this)
  1487. parent->appendProp(path, val);
  1488. else if (child)
  1489. child->appendProp(qualifier, val);
  1490. else
  1491. setProp(path, val);
  1492. }
  1493. }
  1494. bool PTree::getPropBool(const char *xpath, bool dft) const
  1495. {
  1496. const char *val = queryProp(xpath);
  1497. if (val && *val)
  1498. return strToBool(val);
  1499. else
  1500. return dft;
  1501. }
  1502. __int64 PTree::getPropInt64(const char *xpath, __int64 dft) const
  1503. {
  1504. if (!xpath)
  1505. {
  1506. if (!value) return dft;
  1507. else
  1508. {
  1509. const char *v = (const char *)value->queryValue();
  1510. if (!v || !*v) return dft;
  1511. else return _atoi64(v);
  1512. }
  1513. }
  1514. else if (isAttribute(xpath))
  1515. {
  1516. const char *v = getAttributeValue(xpath);
  1517. if (!v || !*v) // intentional return dft if attribute equals ""
  1518. return dft;
  1519. return _atoi64(v);
  1520. }
  1521. else
  1522. {
  1523. const char *prop = splitXPathX(xpath);
  1524. if (isAttribute(prop))
  1525. {
  1526. MAKE_LSTRING(path, xpath, prop-xpath);
  1527. IPropertyTree *branch = queryPropTree(path);
  1528. if (!branch) return dft;
  1529. return branch->getPropInt64(prop, dft);
  1530. }
  1531. else
  1532. {
  1533. IPropertyTree *branch = queryPropTree(xpath);
  1534. if (!branch) return dft;
  1535. return branch->getPropInt64(NULL, dft);
  1536. }
  1537. }
  1538. }
  1539. void PTree::setPropInt64(const char * xpath, __int64 val)
  1540. {
  1541. if (!xpath || '\0' == *xpath)
  1542. {
  1543. char buf[23];
  1544. numtostr(buf, val);
  1545. setLocal((size32_t)strlen(buf)+1, buf);
  1546. }
  1547. else if (isAttribute(xpath))
  1548. {
  1549. char buf[23];
  1550. numtostr(buf, val);
  1551. setAttribute(xpath, buf);
  1552. }
  1553. else
  1554. {
  1555. const char *prop;
  1556. IPropertyTree *branch = splitBranchProp(xpath, prop, true);
  1557. if (isAttribute(prop))
  1558. branch->setPropInt64(prop, val);
  1559. else
  1560. {
  1561. IPropertyTree *propBranch = queryCreateBranch(branch, prop);
  1562. propBranch->setPropInt64(NULL, val);
  1563. }
  1564. }
  1565. }
  1566. void PTree::addPropInt64(const char *xpath, __int64 val)
  1567. {
  1568. if (!xpath || '\0' == *xpath)
  1569. {
  1570. char buf[23];
  1571. numtostr(buf,val);
  1572. addLocal((size32_t)strlen(buf)+1, buf);
  1573. }
  1574. else if (isAttribute(xpath))
  1575. {
  1576. char buf[23];
  1577. numtostr(buf, val);
  1578. setAttribute(xpath, buf);
  1579. }
  1580. else if ('[' == *xpath)
  1581. {
  1582. char buf[23];
  1583. numtostr(buf, val);
  1584. aindex_t pos = getChildMatchPos(xpath);
  1585. if ((aindex_t) -1 == pos)
  1586. throw MakeIPTException(-1, "addPropInt64: qualifier unmatched %s", xpath);
  1587. addLocal((size32_t)strlen(buf)+1, buf, false, pos);
  1588. }
  1589. else
  1590. {
  1591. IPropertyTree *parent, *child;
  1592. StringAttr path, qualifier;
  1593. resolveParentChild(xpath, parent, child, path, qualifier);
  1594. if (parent != this)
  1595. parent->addPropInt64(path, val);
  1596. else if (child)
  1597. child->addPropInt64(qualifier, val);
  1598. else
  1599. setPropInt64(path, val);
  1600. }
  1601. }
  1602. int PTree::getPropInt(const char *xpath, int dft) const
  1603. {
  1604. return (int) getPropInt64(xpath, dft); // underlying type always __int64 (now)
  1605. }
  1606. void PTree::setPropInt(const char *xpath, int val)
  1607. {
  1608. setPropInt64(xpath, val); // underlying type always __int64 (now)
  1609. }
  1610. void PTree::addPropInt(const char *xpath, int val)
  1611. {
  1612. addPropInt64(xpath, val); // underlying type always __int64 (now)
  1613. }
  1614. double PTree::getPropReal(const char *xpath, double dft) const
  1615. {
  1616. const char *val = queryProp(xpath);
  1617. return val?atof(val):dft;
  1618. }
  1619. bool PTree::isCompressed(const char *xpath) const
  1620. {
  1621. if (!xpath)
  1622. return (value && value->isCompressed());
  1623. else if (isAttribute(xpath))
  1624. return false;
  1625. else
  1626. {
  1627. const char *prop = splitXPathX(xpath);
  1628. if (!isAttribute(prop))
  1629. {
  1630. IPropertyTree *branch = queryPropTree(xpath);
  1631. if (branch)
  1632. return branch->isCompressed(nullptr);
  1633. }
  1634. }
  1635. return false;
  1636. }
  1637. bool PTree::isBinary(const char *xpath) const
  1638. {
  1639. if (!xpath)
  1640. return IptFlagTst(flags, ipt_binary);
  1641. else if (isAttribute(xpath)) // still positing that attr cannot be binary for now.
  1642. return false;
  1643. else
  1644. {
  1645. const char *prop = splitXPathX(xpath);
  1646. if (!isAttribute(prop))
  1647. {
  1648. IPropertyTree *branch = queryPropTree(xpath);
  1649. if (branch)
  1650. return branch->isBinary(nullptr);
  1651. }
  1652. }
  1653. return false;
  1654. }
  1655. bool PTree::renameTree(IPropertyTree *child, const char *newName) // really here for hook for SDS (can substationally optimize remote action)
  1656. {
  1657. if (0==strcmp(newName, child->queryName()) && NotFound!=findChild(child)) return false;
  1658. Linked<IPropertyTree> tmp = child;
  1659. if (removeTree(child))
  1660. {
  1661. addPropTree(newName, child);
  1662. tmp.getClear(); // addPropTree has taken ownership.
  1663. return true;
  1664. }
  1665. return false;
  1666. }
  1667. bool PTree::renameProp(const char *xpath, const char *newName)
  1668. {
  1669. if (!xpath || '\0' == *xpath)
  1670. throw MakeIPTException(-1, "renameProp: cannot rename self, renameProp has to rename in context of a parent");
  1671. if (strcmp(xpath,"/")==0) // rename of self allowed assuming no parent
  1672. setName(newName);
  1673. else if ('[' == *xpath)
  1674. UNIMPLEMENTED;
  1675. else if (isAttribute(xpath))
  1676. {
  1677. StringBuffer val;
  1678. if (!getProp(xpath, val))
  1679. return false;
  1680. removeProp(xpath);
  1681. addProp(newName, val.str());
  1682. }
  1683. else
  1684. {
  1685. StringBuffer path;
  1686. const char *prop = splitXPath(xpath, path);
  1687. assertex(prop);
  1688. if (path.length())
  1689. {
  1690. Owned<IPropertyTreeIterator> iter = getElements(path.str());
  1691. if (!iter->first())
  1692. return false;
  1693. IPropertyTree &branch = iter->query();
  1694. if (iter->next())
  1695. AMBIGUOUS_PATH("renameProp", xpath);
  1696. return branch.renameProp(prop, newName);
  1697. }
  1698. else
  1699. {
  1700. IPropertyTree *old = queryPropTree(xpath);
  1701. if (!old)
  1702. return false;
  1703. return renameTree(old, newName);
  1704. }
  1705. }
  1706. return true;
  1707. }
  1708. bool PTree::getPropBin(const char *xpath, MemoryBuffer &ret) const
  1709. {
  1710. CHECK_ATTRIBUTE(xpath);
  1711. if (!xpath)
  1712. {
  1713. if (!value) return true; // exists, but no value
  1714. value->getValue(ret, IptFlagTst(flags, ipt_binary));
  1715. return true;
  1716. }
  1717. else
  1718. {
  1719. const char *prop = splitXPathX(xpath);
  1720. if (isAttribute(prop))
  1721. {
  1722. MAKE_LSTRING(path, xpath, prop-xpath);
  1723. IPropertyTree *branch = queryPropTree(path);
  1724. if (!branch) return false;
  1725. return branch->getPropBin(prop, ret);
  1726. }
  1727. else
  1728. {
  1729. IPropertyTree *branch = queryPropTree(xpath);
  1730. if (!branch) return false;
  1731. return branch->getPropBin(NULL, ret);
  1732. }
  1733. }
  1734. }
  1735. void PTree::setPropBin(const char * xpath, size32_t size, const void *data)
  1736. {
  1737. CHECK_ATTRIBUTE(xpath);
  1738. if (!xpath || '\0' == *xpath)
  1739. setLocal(size, data, true);
  1740. else
  1741. {
  1742. const char *prop;
  1743. IPropertyTree *branch = splitBranchProp(xpath, prop, true);
  1744. if (isAttribute(prop))
  1745. branch->setPropBin(prop, size, data);
  1746. else
  1747. {
  1748. IPropertyTree *propBranch = queryCreateBranch(branch, prop);
  1749. propBranch->setPropBin(NULL, size, data);
  1750. }
  1751. }
  1752. }
  1753. void PTree::addPropBin(const char *xpath, size32_t size, const void *data)
  1754. {
  1755. CHECK_ATTRIBUTE(xpath);
  1756. if (!xpath || '\0' == *xpath)
  1757. addLocal(size, data, true);
  1758. else if ('[' == *xpath)
  1759. {
  1760. aindex_t pos = getChildMatchPos(xpath);
  1761. if ((aindex_t) -1 == pos)
  1762. throw MakeIPTException(-1, "addPropBin: qualifier unmatched %s", xpath);
  1763. addLocal(size, data, true, pos);
  1764. }
  1765. else
  1766. {
  1767. IPropertyTree *parent, *child;
  1768. StringAttr path, qualifier;
  1769. resolveParentChild(xpath, parent, child, path, qualifier);
  1770. if (parent != this)
  1771. parent->addPropBin(path, size, data);
  1772. else if (child)
  1773. child->addPropBin(qualifier, size, data);
  1774. else
  1775. setPropBin(path, size, data);
  1776. }
  1777. }
  1778. void PTree::appendPropBin(const char *xpath, size32_t size, const void *data)
  1779. {
  1780. CHECK_ATTRIBUTE(xpath);
  1781. if (!xpath || '\0' == *xpath)
  1782. appendLocal(size, data, true);
  1783. else if ('[' == *xpath)
  1784. {
  1785. IPropertyTree *qualified = queryPropTree(xpath);
  1786. if (!qualified)
  1787. throw MakeIPTException(-1, "appendPropBin: qualifier unmatched %s", xpath);
  1788. qualified->appendPropBin(nullptr, size, data);
  1789. }
  1790. else
  1791. {
  1792. IPropertyTree *parent, *child;
  1793. StringAttr path, qualifier;
  1794. resolveParentChild(xpath, parent, child, path, qualifier);
  1795. if (parent != this)
  1796. parent->appendPropBin(path, size, data);
  1797. else if (child)
  1798. child->appendPropBin(qualifier, size, data);
  1799. else
  1800. setPropBin(path, size, data);
  1801. }
  1802. }
  1803. IPropertyTree *PTree::getPropTree(const char *xpath) const
  1804. {
  1805. IPropertyTree *tree = queryPropTree(xpath);
  1806. return LINK(tree);
  1807. }
  1808. IPropertyTree *PTree::queryPropTree(const char *xpath) const
  1809. {
  1810. Owned<IPropertyTreeIterator> iter = getElements(xpath);
  1811. IPropertyTree *element = NULL;
  1812. if (iter->first())
  1813. {
  1814. element = &iter->query();
  1815. if (iter->next())
  1816. AMBIGUOUS_PATH("getProp",xpath);
  1817. }
  1818. return element;
  1819. }
  1820. void PTree::replaceSelf(IPropertyTree *val)
  1821. {
  1822. Owned<IAttributeIterator> aiter = getAttributes();
  1823. StringArray attrs;
  1824. ForEach (*aiter)
  1825. attrs.append(aiter->queryName());
  1826. ForEachItemIn(a, attrs)
  1827. removeProp(attrs.item(a));
  1828. ICopyArrayOf<IPropertyTree> elems;
  1829. Owned<IPropertyTreeIterator> iter = getElements("*");
  1830. ForEach(*iter)
  1831. elems.append(iter->query());
  1832. ForEachItemIn(e, elems)
  1833. removeTree(&elems.item(e));
  1834. aiter.setown(val->getAttributes());
  1835. ForEach(*aiter)
  1836. setProp(aiter->queryName(), aiter->queryValue());
  1837. iter.setown(val->getElements("*"));
  1838. ForEach(*iter)
  1839. {
  1840. IPropertyTree &node = iter->query();
  1841. node.Link();
  1842. addPropTree(node.queryName(), &node);
  1843. }
  1844. val->Release();
  1845. }
  1846. IPropertyTree *PTree::setPropTree(const char *xpath, IPropertyTree *val)
  1847. {
  1848. CHECK_ATTRIBUTE(xpath);
  1849. if (NULL == xpath)
  1850. {
  1851. replaceSelf(val);
  1852. return this;
  1853. }
  1854. else
  1855. {
  1856. StringAttr prop, qualifier;
  1857. IPropertyTree *branch, *child;
  1858. resolveParentChild(xpath, branch, child, prop, qualifier);
  1859. if (branch == this)
  1860. {
  1861. IPropertyTree *_val = ownPTree(val);
  1862. dbgassertex(QUERYINTERFACE(_val, PTree));
  1863. PTree *__val = static_cast<PTree *>(_val);
  1864. __val->setName(prop);
  1865. addingNewElement(*_val, ANE_SET);
  1866. if (!checkChildren()) createChildMap();
  1867. children->set(prop, _val);
  1868. return _val;
  1869. }
  1870. else
  1871. return branch->setPropTree(prop, val);
  1872. }
  1873. }
  1874. bool PTree::isArray(const char *xpath) const
  1875. {
  1876. if (!xpath || !*xpath) //item in an array child of parent? I don't think callers ever access array container directly
  1877. return arrayOwner && arrayOwner->isArray();
  1878. else if (isAttribute(xpath))
  1879. return false;
  1880. else
  1881. {
  1882. StringBuffer path;
  1883. const char *prop = splitXPath(xpath, path);
  1884. assertex(prop);
  1885. if (!isAttribute(prop))
  1886. {
  1887. if (path.length())
  1888. {
  1889. Owned<IPropertyTreeIterator> iter = getElements(path.str());
  1890. if (!iter->first())
  1891. return false;
  1892. IPropertyTree &branch = iter->query();
  1893. if (iter->next())
  1894. AMBIGUOUS_PATH("isArray", xpath);
  1895. return branch.isArray(prop);
  1896. }
  1897. else
  1898. {
  1899. IPropertyTree *child = children->query(xpath);
  1900. if (child)
  1901. {
  1902. PTree *tree = static_cast<PTree *>(child);
  1903. return (tree && tree->value && tree->value->isArray());
  1904. }
  1905. }
  1906. }
  1907. }
  1908. return false;
  1909. }
  1910. void PTree::addPTreeArrayItem(IPropertyTree *existing, const char *xpath, PTree *val, aindex_t pos)
  1911. {
  1912. IPropertyTree *iptval = static_cast<IPropertyTree *>(val);
  1913. PTree *tree = nullptr;
  1914. if (existing)
  1915. {
  1916. dbgassertex(QUERYINTERFACE(existing, PTree));
  1917. tree = static_cast<PTree *>(existing);
  1918. if (tree->value && tree->value->isArray())
  1919. {
  1920. val->setOwner(tree->value);
  1921. if ((aindex_t) -1 == pos)
  1922. tree->value->addElement(iptval);
  1923. else
  1924. tree->value->setElement(pos, iptval);
  1925. return;
  1926. }
  1927. }
  1928. IPTArrayValue *array = new CPTArray();
  1929. IPropertyTree *container = create(xpath, array);
  1930. val->setOwner(array);
  1931. if (existing)
  1932. {
  1933. array->addElement(LINK(existing));
  1934. assertex((aindex_t) -1 == pos || 0 == pos);
  1935. if ((aindex_t) -1 == pos)
  1936. array->addElement(iptval);
  1937. else
  1938. array->setElement(0, iptval);
  1939. tree->setOwner(array);
  1940. children->replace(xpath, container);
  1941. }
  1942. else
  1943. {
  1944. array->addElement(iptval);
  1945. children->set(xpath, container);
  1946. }
  1947. }
  1948. IPropertyTree *PTree::addPropTree(const char *xpath, IPropertyTree *val, bool alwaysUseArray)
  1949. {
  1950. if (!xpath || '\0' == *xpath)
  1951. throw MakeIPTException(PTreeExcpt_InvalidTagName, "Invalid xpath for property tree insertion specified");
  1952. else
  1953. {
  1954. CHECK_ATTRIBUTE(xpath);
  1955. const char *x = xpath;
  1956. for (;;)
  1957. {
  1958. if (!*x++)
  1959. {
  1960. IPropertyTree *_val = ownPTree(val);
  1961. dbgassertex(QUERYINTERFACE(_val, PTree));
  1962. PTree *__val = static_cast<PTree *>(_val);
  1963. /* NB: potentially param xpath is a reference to the existing name.
  1964. * So fetch new name ptr after set.
  1965. */
  1966. __val->setName(xpath);
  1967. xpath = __val->queryName();
  1968. addingNewElement(*_val, -1);
  1969. if (checkChildren())
  1970. {
  1971. IPropertyTree *child = children->query(xpath);
  1972. if (child)
  1973. {
  1974. addPTreeArrayItem(child, xpath, __val);
  1975. return _val;
  1976. }
  1977. }
  1978. else
  1979. createChildMap();
  1980. if (alwaysUseArray)
  1981. addPTreeArrayItem(nullptr, xpath, __val);
  1982. else
  1983. children->set(xpath, _val);
  1984. return _val;
  1985. }
  1986. if ('/' == *x || '[' == *x)
  1987. break;
  1988. }
  1989. IPropertyTree *parent, *child;
  1990. StringAttr path, qualifier;
  1991. resolveParentChild(xpath, parent, child, path, qualifier);
  1992. if (parent != this)
  1993. return parent->addPropTree(path, val);
  1994. else
  1995. {
  1996. aindex_t pos = (aindex_t)-1;
  1997. if (!qualifier.isEmpty())
  1998. {
  1999. pos = ((PTree *)child)->getChildMatchPos(qualifier);
  2000. if ((aindex_t) -1 == pos)
  2001. throw MakeIPTException(-1, "addPropTree: qualifier unmatched %s", xpath);
  2002. }
  2003. IPropertyTree *_val = ownPTree(val);
  2004. dbgassertex(QUERYINTERFACE(_val, PTree));
  2005. PTree *__val = static_cast<PTree *>(_val);
  2006. __val->setName(path);
  2007. addingNewElement(*_val, pos);
  2008. if (child)
  2009. {
  2010. addPTreeArrayItem(child, path, __val, pos);
  2011. }
  2012. else
  2013. {
  2014. if (!checkChildren()) createChildMap();
  2015. if (alwaysUseArray)
  2016. addPTreeArrayItem(nullptr, path, __val);
  2017. else
  2018. children->set(path, _val);
  2019. children->set(path, _val);
  2020. }
  2021. return _val;
  2022. }
  2023. }
  2024. }
  2025. IPropertyTree *PTree::addPropTree(const char *xpath, IPropertyTree *val)
  2026. {
  2027. return addPropTree(xpath, val, false);
  2028. }
  2029. IPropertyTree *PTree::addPropTreeArrayItem(const char *xpath, IPropertyTree *val)
  2030. {
  2031. return addPropTree(xpath, val, true);
  2032. }
  2033. bool PTree::removeTree(IPropertyTree *child)
  2034. {
  2035. if (child == this)
  2036. throw MakeIPTException(-1, "Cannot remove self");
  2037. if (checkChildren())
  2038. {
  2039. IPropertyTree *_child = children->query(child->queryName());
  2040. if (_child)
  2041. {
  2042. if (child == _child)
  2043. return children->removeExact(child);
  2044. else
  2045. {
  2046. IPTArrayValue *value = ((PTree *)_child)->queryValue();
  2047. if (value && value->isArray())
  2048. {
  2049. unsigned pos = value->find(child);
  2050. if (NotFound != pos)
  2051. {
  2052. removingElement(child, pos);
  2053. value->removeElement(pos);
  2054. if (0 == value->elements())
  2055. children->removeExact(_child);
  2056. return true;
  2057. }
  2058. }
  2059. }
  2060. }
  2061. }
  2062. return false;
  2063. }
  2064. bool PTree::removeProp(const char *xpath)
  2065. {
  2066. if (xpath && isAttribute(xpath))
  2067. return removeAttribute(xpath);
  2068. StringBuffer path;
  2069. const char *prop = splitXPath(xpath, path);
  2070. if (!prop)
  2071. throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Invalid xpath for property deletion");
  2072. if (path.length())
  2073. {
  2074. Owned<IPropertyTreeIterator> iter = getElements(path.str());
  2075. if (!iter)
  2076. return false;
  2077. bool res = false;
  2078. if (iter->first())
  2079. {
  2080. do
  2081. {
  2082. IPropertyTree *branch = &iter->query();
  2083. if (branch) {
  2084. res = branch->removeProp(prop);
  2085. if (res)
  2086. break; // deleted first may be another
  2087. }
  2088. }
  2089. while (iter->next());
  2090. }
  2091. return res;
  2092. }
  2093. else
  2094. {
  2095. if (!queryNextUnquoted(xpath, '[') && !strchr(prop, '*')) // have to work hard to locate qualified prop tree from parent.
  2096. {
  2097. if (!checkChildren()) return false;
  2098. return children->remove(prop); // NB: might be multivalued.
  2099. }
  2100. const char *xxpath = prop;
  2101. readID(xxpath, false);
  2102. const char *idEnd = xxpath;
  2103. if ('[' == *xxpath)
  2104. {
  2105. ++xxpath;
  2106. const char *digitStart = xxpath;
  2107. while (*xxpath && ']' != *xxpath && isdigit(*xxpath)) xxpath++;
  2108. assertex(*xxpath != '\0');
  2109. if (']' == *xxpath) // so it's a digit index!
  2110. {
  2111. StringAttr id(prop, idEnd-prop);
  2112. PTree *child = children?(PTree *)children->query(id):NULL;
  2113. if (child)
  2114. {
  2115. if (child->value && child->value->isArray() && child->value->elements()>1)
  2116. {
  2117. StringAttr digit(digitStart, xxpath-digitStart);
  2118. unsigned i = atoi(digit);
  2119. if (i && i <= child->value->elements())
  2120. {
  2121. removingElement(child->value->queryElement(i-1), i-1);
  2122. child->value->removeElement(i-1);
  2123. return true;
  2124. }
  2125. }
  2126. else
  2127. return children->removeExact(child);
  2128. }
  2129. return false;
  2130. }
  2131. }
  2132. // JCSMORE - This is ridiculous for qualifier have to iterate to find match ok, but then finding where that *was* gees!
  2133. Owned <IPropertyTreeIterator> iter = getElements(prop);
  2134. if (!iter->first())
  2135. return false;
  2136. IPropertyTree *match = &iter->query();
  2137. #if 0 // intentionally removes first encountered
  2138. if (iter->next())
  2139. {
  2140. AMBIGUOUS_PATH("removeProp",xpath);
  2141. }
  2142. #endif
  2143. return removeTree(match);
  2144. }
  2145. return false;
  2146. }
  2147. aindex_t PTree::queryChildIndex(IPropertyTree *child)
  2148. {
  2149. return findChild(child);
  2150. }
  2151. StringBuffer &PTree::getName(StringBuffer &ret) const
  2152. {
  2153. ret.append(queryName());
  2154. return ret;
  2155. }
  2156. typedef CopyReferenceArrayOf<AttrValue> AttrArray;
  2157. IAttributeIterator *PTree::getAttributes(bool sorted) const
  2158. {
  2159. class CAttributeIterator : implements IAttributeIterator, public CInterface
  2160. {
  2161. Linked<const PTree> parent;
  2162. AttrValue *cur = nullptr;
  2163. public:
  2164. IMPLEMENT_IINTERFACE;
  2165. CAttributeIterator(const PTree *_parent) : parent(_parent)
  2166. {
  2167. }
  2168. // IAttributeIterator impl.
  2169. virtual bool first() override
  2170. {
  2171. cur = parent->getNextAttribute(nullptr);
  2172. return cur ? true : false;
  2173. }
  2174. virtual bool next() override
  2175. {
  2176. cur = parent->getNextAttribute(cur);
  2177. return cur ? true : false;
  2178. }
  2179. virtual bool isValid() override { return cur ? true : false; }
  2180. virtual const char *queryName() const override
  2181. {
  2182. return cur->key.get();
  2183. }
  2184. virtual const char *queryValue() const override
  2185. {
  2186. return cur->value.get();
  2187. }
  2188. virtual StringBuffer &getValue(StringBuffer &out) override
  2189. {
  2190. out.append(queryValue());
  2191. return out;
  2192. }
  2193. virtual unsigned count() override { return parent->getAttributeCount(); }
  2194. };
  2195. class CSortedAttributeIterator : implements IAttributeIterator, public CInterface
  2196. {
  2197. typedef ArrayIteratorOf<AttrArray, AttrValue &> AttrIterator;
  2198. AttrArray attrs;
  2199. AttrValue *cur;
  2200. AttrIterator *iter;
  2201. Linked<const PTree> parent;
  2202. public:
  2203. IMPLEMENT_IINTERFACE;
  2204. static int compareAttrs(AttrValue * const *ll, AttrValue * const *rr)
  2205. {
  2206. return stricmp((*ll)->key.get(), (*rr)->key.get());
  2207. };
  2208. CSortedAttributeIterator(const PTree *_parent) : cur(NULL), iter(NULL), parent(_parent)
  2209. {
  2210. AttrValue *cur = parent->getNextAttribute(nullptr);
  2211. if (cur)
  2212. {
  2213. do
  2214. {
  2215. attrs.append(*cur);
  2216. cur = parent->getNextAttribute(cur);
  2217. }
  2218. while (cur);
  2219. attrs.sort(compareAttrs);
  2220. iter = new AttrIterator(attrs);
  2221. }
  2222. }
  2223. ~CSortedAttributeIterator()
  2224. {
  2225. if (iter)
  2226. delete iter;
  2227. }
  2228. // IAttributeIterator impl.
  2229. virtual bool first() override
  2230. {
  2231. if (!iter) return false;
  2232. if (!iter->first()) { cur = NULL; return false; }
  2233. cur = &iter->query();
  2234. return true;
  2235. }
  2236. virtual bool next() override
  2237. {
  2238. if (!iter) return false;
  2239. if (!iter->next()) { cur = NULL; return false; }
  2240. cur = &iter->query();
  2241. return true;
  2242. }
  2243. virtual bool isValid() override { return cur!=NULL; }
  2244. virtual const char *queryName() const override
  2245. {
  2246. assertex(cur);
  2247. return cur->key.get();
  2248. }
  2249. virtual const char *queryValue() const override
  2250. {
  2251. assertex(cur);
  2252. return cur->value.get();
  2253. }
  2254. virtual StringBuffer &getValue(StringBuffer &out) override
  2255. {
  2256. assertex(cur);
  2257. return out.append(queryValue());
  2258. }
  2259. virtual unsigned count() override { return attrs.ordinality(); }
  2260. };
  2261. if (sorted)
  2262. return new CSortedAttributeIterator(this);
  2263. else
  2264. return new CAttributeIterator(this);
  2265. }
  2266. ///////////////////
  2267. class CIndexIterator : implements IPropertyTreeIterator, public CInterface
  2268. {
  2269. Owned<IPropertyTreeIterator> subIter;
  2270. IPropertyTree *celem;
  2271. unsigned index, current;
  2272. public:
  2273. IMPLEMENT_IINTERFACE;
  2274. CIndexIterator(IPropertyTreeIterator *_subIter, unsigned _index) : subIter(_subIter), index(_index)
  2275. {
  2276. }
  2277. // IPropertyTreeIterator
  2278. virtual bool first() override
  2279. {
  2280. if (!index)
  2281. return false;
  2282. if (!subIter->first())
  2283. return false;
  2284. current = 1;
  2285. celem = NULL;
  2286. do
  2287. {
  2288. if (current == index)
  2289. {
  2290. celem = &subIter->query();
  2291. return true;
  2292. }
  2293. if (!subIter->next())
  2294. return false;
  2295. } while (++current <= index);
  2296. return false;
  2297. }
  2298. virtual bool isValid() override
  2299. {
  2300. return celem && (index >= current);
  2301. }
  2302. virtual bool next() override
  2303. {
  2304. celem = NULL;
  2305. return false;
  2306. }
  2307. virtual IPropertyTree & query() override
  2308. {
  2309. return *celem;
  2310. }
  2311. };
  2312. IPropertyTreeIterator *PTree::getElements(const char *xpath, IPTIteratorCodes flags) const
  2313. {
  2314. // NULL iterator for local value (i.e. maybe be single value or array)
  2315. if (NULL == xpath || '\0' == *xpath)
  2316. return new SingleIdIterator(*this);
  2317. Owned<IPropertyTreeIterator> iter;
  2318. const char *_xpath = xpath;
  2319. bool root=true;
  2320. restart:
  2321. switch (*xpath)
  2322. {
  2323. case '.':
  2324. root=false;
  2325. ++xpath;
  2326. if ('\0' == *xpath)
  2327. return new SingleIdIterator(*this);
  2328. else if ('/' != *xpath)
  2329. throw MakeXPathException(xpath-1, PTreeExcpt_XPath_Unsupported, 0, "\"/\" expected");
  2330. goto restart;
  2331. case '/':
  2332. ++xpath;
  2333. if ('/' == *xpath)
  2334. {
  2335. iter.setown(getElements(xpath+1));
  2336. if (checkChildren())
  2337. {
  2338. IPropertyTreeIterator *iter2 = new PTIdMatchIterator(this, "*", isnocase(), flags & iptiter_sort);
  2339. iter2 = new PTStackIterator(iter2, xpath-1);
  2340. SeriesPTIterator *series = new SeriesPTIterator();
  2341. series->addIterator(iter.getClear());
  2342. series->addIterator(iter2);
  2343. return series;
  2344. }
  2345. else
  2346. return iter.getClear();
  2347. }
  2348. else if (root)
  2349. throw MakeXPathException(xpath, PTreeExcpt_XPath_Unsupported, 0, "Root specifier \"/\" specifier is not supported");
  2350. else if ('\0' == *xpath)
  2351. return new SingleIdIterator(*this);
  2352. goto restart;
  2353. case '[':
  2354. {
  2355. ++xpath;
  2356. if (isdigit(*xpath)) {
  2357. StringAttr index;
  2358. xpath = readIndex(xpath, index);
  2359. unsigned i = atoi(index.get());
  2360. if (i)
  2361. {
  2362. if (value && value->isArray())
  2363. {
  2364. IPropertyTree *element = value->queryElement(--i);
  2365. if (element)
  2366. {
  2367. iter.setown(element->getElements(NULL));
  2368. }
  2369. }
  2370. else if (i == 1)
  2371. iter.setown(new SingleIdIterator(*this));
  2372. }
  2373. }
  2374. else
  2375. {
  2376. if (checkPattern(xpath))
  2377. iter.setown(new SingleIdIterator(*this));
  2378. }
  2379. if (']' != *xpath)
  2380. throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
  2381. ++xpath;
  2382. break;
  2383. }
  2384. default:
  2385. {
  2386. bool wild;
  2387. const char *start = xpath;
  2388. readWildId(xpath, wild);
  2389. size32_t s = xpath-start;
  2390. if (s)
  2391. {
  2392. MAKE_LSTRING(id, start, s);
  2393. if (checkChildren())
  2394. {
  2395. IPropertyTree *child = NULL;
  2396. if (!wild)
  2397. child = children->query(id);
  2398. if ((wild || child) && '[' == *xpath) // check for local index not iterative qualifier.
  2399. {
  2400. const char *xxpath = xpath+1;
  2401. if (isdigit(*xxpath)) {
  2402. StringAttr idxstr;
  2403. xxpath = readIndex(xxpath, idxstr);
  2404. if (']' != *xxpath)
  2405. throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
  2406. ++xxpath;
  2407. unsigned index = atoi(idxstr.get());
  2408. if (index)
  2409. {
  2410. Owned<IPropertyTreeIterator> _iter = getElements(id);
  2411. if (_iter->first())
  2412. {
  2413. do
  2414. {
  2415. if (0 == --index)
  2416. {
  2417. iter.setown(new SingleIdIterator((PTree &)_iter->query()));
  2418. break;
  2419. }
  2420. }
  2421. while (_iter->next());
  2422. }
  2423. }
  2424. xpath = xxpath;
  2425. }
  2426. else
  2427. {
  2428. const char *start = xxpath-1;
  2429. for (;;)
  2430. {
  2431. char quote = 0;
  2432. while (']' != *(++xxpath) || quote)
  2433. {
  2434. switch (*xxpath) {
  2435. case '\"':
  2436. case '\'':
  2437. {
  2438. if (quote)
  2439. {
  2440. if (*xxpath == quote)
  2441. quote = 0;
  2442. }
  2443. else
  2444. quote = *xxpath;
  2445. break;
  2446. }
  2447. case '\0':
  2448. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xxpath-start, "Qualifier brace unclosed");
  2449. }
  2450. }
  2451. ++xxpath;
  2452. if ('[' == *xxpath)
  2453. {
  2454. ++xxpath;
  2455. if (isdigit(*xxpath))
  2456. {
  2457. const char *lhsStart = start+1;
  2458. Owned<IPropertyTreeIterator> siter = checkMapIterator(lhsStart, *child);
  2459. if (!siter)
  2460. {
  2461. if (wild)
  2462. iter.setown(new PTIdMatchIterator(this, id, isnocase(), flags & iptiter_sort));
  2463. else
  2464. iter.setown(child->getElements(NULL));
  2465. StringAttr qualifier(start, (xxpath-1)-start);
  2466. siter.setown(new PTStackIterator(iter.getClear(), qualifier.get()));
  2467. }
  2468. StringAttr index;
  2469. xxpath = readIndex(xxpath, index);
  2470. unsigned i = atoi(index.get());
  2471. iter.setown(new CIndexIterator(siter.getClear(), i));
  2472. ++xxpath;
  2473. break;
  2474. }
  2475. }
  2476. else
  2477. {
  2478. if (!wild)
  2479. {
  2480. const char *lhsStart = start+1;
  2481. Owned<IPropertyTreeIterator> mapIter = checkMapIterator(lhsStart, *child);
  2482. if (mapIter)
  2483. {
  2484. xxpath = lhsStart;
  2485. iter.swap(mapIter);
  2486. break;
  2487. }
  2488. }
  2489. if (wild)
  2490. iter.setown(new PTIdMatchIterator(this, id, isnocase(), flags & iptiter_sort));
  2491. else
  2492. iter.setown(child->getElements(NULL));
  2493. StringAttr qualifier(start, xxpath-start);
  2494. iter.setown(new PTStackIterator(iter.getClear(), qualifier.get()));
  2495. break;
  2496. }
  2497. }
  2498. xpath = xxpath;
  2499. }
  2500. }
  2501. else
  2502. {
  2503. if (wild)
  2504. iter.setown(new PTIdMatchIterator(this, id, isnocase(), flags & iptiter_sort));
  2505. else if (child)
  2506. iter.setown(child->getElements(NULL));
  2507. }
  2508. }
  2509. }
  2510. break;
  2511. }
  2512. }
  2513. if (!iter)
  2514. iter.setown(LINK(nullPTreeIterator));
  2515. if (*xpath == '\0' || (*xpath == '/' && '\0' == *(xpath+1)))
  2516. return iter.getClear();
  2517. else
  2518. return new PTStackIterator(iter.getClear(), xpath);
  2519. }
  2520. void PTree::localizeElements(const char *xpath, bool allTail)
  2521. {
  2522. // null action for local ptree
  2523. }
  2524. unsigned PTree::numChildren()
  2525. {
  2526. if (!checkChildren()) return 0;
  2527. return children->numChildren();
  2528. }
  2529. unsigned PTree::getCount(const char *xpath)
  2530. {
  2531. unsigned c=0;
  2532. Owned<IPropertyTreeIterator> iter = getElements(xpath);
  2533. ForEach(*iter)
  2534. ++c;
  2535. return c;
  2536. }
  2537. void getXPathMatchTree(IPropertyTree &parentContext, const char *xpath, IPropertyTree *&matchContainer)
  2538. {
  2539. if (!xpath || !*xpath)
  2540. {
  2541. matchContainer = createPTree(parentContext.queryName());
  2542. return;
  2543. }
  2544. StringBuffer head;
  2545. const char *str = xpath;
  2546. const char *end = str+strlen(xpath);
  2547. bool quote = false;
  2548. bool inQualifier = false;
  2549. bool done = false;
  2550. bool recurse = false;
  2551. while (end != str)
  2552. {
  2553. switch (*str) {
  2554. case '"':
  2555. if (quote) quote = false;
  2556. else quote = true;
  2557. break;
  2558. case '[':
  2559. if (inQualifier)
  2560. {
  2561. if (!quote)
  2562. throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, str-xpath, "Unclosed qualifier detected");
  2563. }
  2564. else
  2565. inQualifier = true;
  2566. break;
  2567. case ']':
  2568. if (inQualifier)
  2569. {
  2570. if (!quote)
  2571. inQualifier = false;
  2572. }
  2573. else if (!quote)
  2574. throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, str-xpath, "Unopened qualifier detected");
  2575. break;
  2576. case '/':
  2577. if (!quote && !inQualifier)
  2578. {
  2579. if ('/' == *(str+1))
  2580. recurse = true;
  2581. done = true;
  2582. }
  2583. break;
  2584. }
  2585. if (done) break;
  2586. ++str;
  2587. }
  2588. const char *tail;
  2589. if (str==end) // top-level matches
  2590. {
  2591. head.append(xpath);
  2592. if (0 == head.length())
  2593. {
  2594. matchContainer = createPTree(xpath);
  2595. return;
  2596. }
  2597. tail = NULL;
  2598. }
  2599. else
  2600. {
  2601. head.append(str-xpath, xpath);
  2602. if (recurse)
  2603. tail = str+2;
  2604. else
  2605. tail = str+1;
  2606. }
  2607. Owned<IPropertyTreeIterator> parentIter = parentContext.getElements(head.str());
  2608. Owned<IPropertyTree> matchParent;
  2609. ForEach (*parentIter)
  2610. {
  2611. IPropertyTree &parent = parentIter->query();
  2612. if (!matchParent)
  2613. matchParent.setown(createPTree(parentContext.queryName()));
  2614. if (tail && *tail)
  2615. {
  2616. IPropertyTree *childContainer = NULL;
  2617. getXPathMatchTree(parent, tail, childContainer);
  2618. if (childContainer)
  2619. {
  2620. if (!head.length())
  2621. matchParent.setown(childContainer);
  2622. else
  2623. {
  2624. unsigned pos = ((PTree &)parentContext).findChild(&parent);
  2625. matchParent->addPropTree(childContainer->queryName(), childContainer);
  2626. childContainer->setPropInt("@pos", pos+1);
  2627. }
  2628. if (!matchContainer)
  2629. matchContainer = LINK(matchParent);
  2630. }
  2631. if (recurse)
  2632. {
  2633. Owned<IPropertyTreeIterator> iter = parent.getElements("*");
  2634. ForEach (*iter)
  2635. {
  2636. IPropertyTree *childContainer = NULL;
  2637. IPropertyTree &child = iter->query();
  2638. getXPathMatchTree(child, xpath, childContainer);
  2639. if (childContainer)
  2640. {
  2641. unsigned pos = ((PTree &)parent).findChild(&child);
  2642. matchParent->addPropTree(childContainer->queryName(), childContainer);
  2643. childContainer->setPropInt("@pos", pos+1);
  2644. if (!matchContainer)
  2645. matchContainer = LINK(matchParent);
  2646. }
  2647. }
  2648. }
  2649. }
  2650. else
  2651. {
  2652. if (&parent != &parentContext)
  2653. {
  2654. IPropertyTree *childContainer = matchParent->addPropTree(parent.queryName(), createPTree());
  2655. unsigned pos = ((PTree &)parentContext).findChild(&parent);
  2656. childContainer->setPropInt("@pos", pos+1);
  2657. }
  2658. if (!matchContainer)
  2659. matchContainer = LINK(matchParent);
  2660. }
  2661. }
  2662. }
  2663. IPropertyTree *getXPathMatchTree(IPropertyTree &parent, const char *xpath)
  2664. {
  2665. IPropertyTree *matchTree = NULL;
  2666. getXPathMatchTree(parent, xpath, matchTree);
  2667. return matchTree;
  2668. }
  2669. void PTree::serializeAttributes(MemoryBuffer &tgt)
  2670. {
  2671. IAttributeIterator *aIter = getAttributes();
  2672. if (aIter->first())
  2673. {
  2674. do
  2675. {
  2676. tgt.append(aIter->queryName());
  2677. tgt.append(aIter->queryValue());
  2678. }
  2679. while (aIter->next());
  2680. }
  2681. tgt.append(""); // attribute terminator. i.e. blank attr name.
  2682. aIter->Release();
  2683. }
  2684. void PTree::serializeSelf(MemoryBuffer &tgt)
  2685. {
  2686. const char *_name = queryName();
  2687. tgt.append(_name ? _name : "");
  2688. tgt.append(flags);
  2689. serializeAttributes(tgt);
  2690. if (value)
  2691. value->serialize(tgt);
  2692. else
  2693. tgt.append((size32_t)0);
  2694. }
  2695. void PTree::serializeCutOff(MemoryBuffer &tgt, int cutoff, int depth)
  2696. {
  2697. serializeSelf(tgt);
  2698. if (-1 == cutoff || depth<cutoff)
  2699. {
  2700. Owned<IPropertyTreeIterator> iter = getElements("*");
  2701. if (iter->first())
  2702. {
  2703. do
  2704. {
  2705. IPropertyTree *_child = &iter->query();
  2706. PTree *child = QUERYINTERFACE(_child, PTree); assertex(child);
  2707. child->serializeCutOff(tgt, cutoff, depth+1);
  2708. }
  2709. while (iter->next());
  2710. }
  2711. }
  2712. tgt.append(""); // element terminator. i.e. blank child name.
  2713. }
  2714. // serializable impl.
  2715. void PTree::serialize(MemoryBuffer &tgt)
  2716. {
  2717. serializeCutOff(tgt, -1, 0);
  2718. }
  2719. void PTree::deserialize(MemoryBuffer &src)
  2720. {
  2721. deserializeSelf(src);
  2722. StringAttr eName;
  2723. for (;;)
  2724. {
  2725. size32_t pos = src.getPos();
  2726. src.read(eName);
  2727. if (eName.isEmpty())
  2728. break;
  2729. src.reset(pos); // reset to re-read tree name
  2730. IPropertyTree *child = create(src);
  2731. addPropTree(eName, child);
  2732. }
  2733. }
  2734. void PTree::deserializeSelf(MemoryBuffer &src)
  2735. {
  2736. setName(NULL); // needs to be cleared before flags changed
  2737. StringAttr _name;
  2738. src.read(_name);
  2739. src.read(flags);
  2740. if (_name[0]==0)
  2741. setName(NULL);
  2742. else
  2743. setName(_name);
  2744. StringAttr attrName, attrValue;
  2745. for (;;)
  2746. {
  2747. src.read(attrName);
  2748. if (attrName.isEmpty())
  2749. break;
  2750. src.read(attrValue);
  2751. setProp(attrName, attrValue);
  2752. }
  2753. size32_t size;
  2754. unsigned pos = src.getPos();
  2755. src.read(size);
  2756. if (value) delete value;
  2757. if (size)
  2758. {
  2759. src.reset(pos);
  2760. value = new CPTValue(src);
  2761. }
  2762. else value = NULL;
  2763. }
  2764. IPropertyTree *PTree::clone(IPropertyTree &srcTree, bool self, bool sub)
  2765. {
  2766. IPropertyTree *_dstTree = self ? this : create(srcTree.queryName());
  2767. PTree *dstTree = QUERYINTERFACE(_dstTree, PTree);
  2768. dbgassertex(dstTree);
  2769. if (self)
  2770. dstTree->setName(srcTree.queryName());
  2771. clone(srcTree, *dstTree, sub);
  2772. return _dstTree;
  2773. }
  2774. void PTree::clone(IPropertyTree &srcTree, IPropertyTree &dstTree, bool sub)
  2775. {
  2776. PTree *_dstTree = QUERYINTERFACE((&dstTree), PTree); assertex(_dstTree); //JCSMORE
  2777. flags = _dstTree->flags;
  2778. if (srcTree.isBinary(NULL))
  2779. {
  2780. MemoryBuffer mb;
  2781. verifyex(srcTree.getPropBin(NULL, mb));
  2782. dstTree.setPropBin(NULL, mb.length(), mb.toByteArray());
  2783. }
  2784. else if (srcTree.isCompressed(NULL))
  2785. {
  2786. StringBuffer s;
  2787. verifyex(srcTree.getProp(NULL, s));
  2788. dstTree.setProp(NULL, s.str());
  2789. }
  2790. else
  2791. dstTree.setProp(NULL, srcTree.queryProp(NULL));
  2792. IAttributeIterator *attrs = srcTree.getAttributes();
  2793. if (attrs->first())
  2794. {
  2795. do
  2796. {
  2797. dstTree.setProp(attrs->queryName(), attrs->queryValue());
  2798. }
  2799. while (attrs->next());
  2800. }
  2801. attrs->Release();
  2802. if (sub)
  2803. {
  2804. Owned<IPropertyTreeIterator> iter = srcTree.getElements("*");
  2805. if (iter->first())
  2806. {
  2807. do
  2808. {
  2809. IPropertyTree &child = iter->query();
  2810. IPropertyTree *newChild = clone(child, false, sub);
  2811. dstTree.addPropTree(newChild->queryName(), newChild);
  2812. }
  2813. while (iter->next());
  2814. }
  2815. }
  2816. }
  2817. IPropertyTree *PTree::ownPTree(IPropertyTree *tree)
  2818. {
  2819. if (!isEquivalent(tree) || tree->IsShared() || isCaseInsensitive() != tree->isCaseInsensitive())
  2820. {
  2821. IPropertyTree *newTree = clone(*tree);
  2822. tree->Release();
  2823. return newTree;
  2824. }
  2825. else
  2826. return tree;
  2827. }
  2828. IPropertyTree *PTree::queryCreateBranch(IPropertyTree *branch, const char *prop, bool *newBranch)
  2829. {
  2830. IPropertyTree *childBranch = branch->queryPropTree(prop);
  2831. if (!childBranch)
  2832. {
  2833. if (newBranch) *newBranch = true;
  2834. childBranch = create(prop);
  2835. branch->setPropTree(prop, childBranch);
  2836. }
  2837. else if (newBranch) *newBranch = false;
  2838. return childBranch;
  2839. }
  2840. IPropertyTree *PTree::splitBranchProp(const char *xpath, const char *&prop, bool error)
  2841. {
  2842. prop = splitXPathX(xpath);
  2843. MAKE_LSTRING(path, xpath, prop-xpath);
  2844. IPropertyTree *branch = queryPropTree(path);
  2845. if (!branch && error)
  2846. throw MakeIPTException(-1, "path %s not found, when setting prop %s", path, xpath);
  2847. return branch;
  2848. }
  2849. IPropertyTree *_createPropBranch(IPropertyTree *tree, const char *xpath, bool createIntermediates, IPropertyTree *&created, IPropertyTree *&createdParent)
  2850. {
  2851. const char *prop;
  2852. StringBuffer path;
  2853. prop = splitXPathUQ(xpath, path);
  2854. IPropertyTree *branch = tree->queryPropTree(path.str());
  2855. if (!branch)
  2856. {
  2857. if (path.length() == strlen(xpath))
  2858. throw MakeIPTException(-1, "createPropBranch: cannot create path : %s", xpath);
  2859. if (!createIntermediates)
  2860. throw MakeIPTException(-1, "createPropBranch: no path found for : %s", path.str());
  2861. if ('/' == path.charAt(path.length()-1))
  2862. path.remove(path.length()-1, 1);
  2863. branch = _createPropBranch(tree, path.str(), createIntermediates, created, createdParent);
  2864. assertex(branch);
  2865. }
  2866. if (prop && '\0' != *prop && '@' != *prop)
  2867. {
  2868. IPropertyTree *_branch = branch->queryPropTree(prop);
  2869. if (_branch)
  2870. branch = _branch;
  2871. else
  2872. {
  2873. IPropertyTree *p = branch;
  2874. branch = branch->addPropTree(prop, createPTree());
  2875. if (!created) { created = branch; createdParent = p; }
  2876. }
  2877. }
  2878. return branch;
  2879. }
  2880. IPropertyTree *createPropBranch(IPropertyTree *tree, const char *xpath, bool createIntermediates, IPropertyTree **created, IPropertyTree **createdParent)
  2881. {
  2882. IPropertyTree *_created = NULL, *_createdParent = NULL;
  2883. try
  2884. {
  2885. IPropertyTree *ret = _createPropBranch(tree, xpath, createIntermediates, _created, _createdParent);
  2886. if (created) *created = _created;
  2887. if (createdParent) *createdParent = _createdParent;
  2888. return ret;
  2889. }
  2890. catch (...)
  2891. {
  2892. if (_created) (_createdParent)->removeTree(_created);
  2893. throw;
  2894. }
  2895. }
  2896. void PTree::addLocal(size32_t l, const void *data, bool _binary, int pos)
  2897. {
  2898. if (!l) return; // right thing to do on addProp("x", NULL) ?
  2899. IPTArrayValue *newValue = new CPTValue(l, data, _binary);
  2900. Owned<IPropertyTree> tree = create(queryName(), newValue);
  2901. PTree *_tree = QUERYINTERFACE(tree.get(), PTree); assertex(_tree);
  2902. if (_binary)
  2903. IptFlagSet(_tree->flags, ipt_binary);
  2904. else
  2905. IptFlagClr(_tree->flags, ipt_binary);
  2906. addingNewElement(*tree, pos);
  2907. IPTArrayValue *array;
  2908. if (value && value->isArray())
  2909. {
  2910. array = value;
  2911. if (pos != -1 && ((unsigned)pos > array->elements()))
  2912. throw MakeIPTException(-1, "Error trying to insert element at %d of %d", pos, array->elements());
  2913. }
  2914. else
  2915. {
  2916. if (pos > 0)
  2917. throw MakeIPTException(-1, "Error trying to insert element at %d of 0", pos);
  2918. // detach children and attributes of this branch now owned by element of newly created array.
  2919. IPropertyTree *element1 = detach();
  2920. array = new CPTArray();
  2921. addingNewElement(*element1, ANE_APPEND);
  2922. array->addElement(element1);
  2923. value = array;
  2924. }
  2925. _tree->setOwner(array);
  2926. tree->Link();
  2927. if (-1 == pos)
  2928. array->addElement(tree);
  2929. else
  2930. array->setElement(pos, tree);
  2931. }
  2932. enum exprType { t_none, t_equality, t_inequality, t_lteq, t_lt, t_gt, t_gteq } tType;
  2933. inline bool match(bool wild, bool numeric, const char *xpath, exprType t, const char *value, unsigned len, const char *pat, unsigned patLen, bool nocase)
  2934. {
  2935. int m;
  2936. if (numeric)
  2937. {
  2938. __int64 lhsN = atoi64_l(value, len);
  2939. __int64 rhsN = atoi64_l(pat, patLen);
  2940. m = lhsN<rhsN?-1:lhsN>rhsN?1:0;
  2941. }
  2942. else if (wild)
  2943. m = false==WildMatch(value, len, pat, patLen, nocase);
  2944. else
  2945. {
  2946. if (len == patLen)
  2947. m = nocase ? memicmp(value, pat, len) : memcmp(value, pat, len);
  2948. else if (len < patLen)
  2949. m = -1;
  2950. else
  2951. m = 1;
  2952. }
  2953. switch (t)
  2954. {
  2955. case t_inequality:
  2956. return m!=0;
  2957. case t_lt:
  2958. return m<0;
  2959. case t_lteq:
  2960. return m<=0;
  2961. case t_equality:
  2962. return m==0;
  2963. case t_gteq:
  2964. return m>=0;
  2965. case t_gt:
  2966. return m>0;
  2967. }
  2968. throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Invalid xpath qualifier expression in xpath: %s", xpath);
  2969. }
  2970. bool PTree::checkPattern(const char *&xxpath) const
  2971. {
  2972. // Pattern is an additional filter at the current node level
  2973. // It can be [condition], or it can be empty (we don't support anything else)
  2974. // supported conditions are:
  2975. // tag - must have child called tag
  2976. // @attr - must have attribute called attr
  2977. // tag="value" - must have child called tag with given value
  2978. // @attr="value" - must have attribute called attr with given value
  2979. const char *xpath = xxpath;
  2980. while (*xpath == ' ' || *xpath == '\t') xpath++;
  2981. const char *start = xpath;
  2982. bool wild = false, nocase = isnocase();
  2983. if (*xpath=='@')
  2984. xpath++;
  2985. char quote = 0;
  2986. const char *lhsEnd, *quoteBegin, *quoteEnd, *rhsBegin, *rhsEnd;
  2987. lhsEnd = quoteBegin = quoteEnd = rhsBegin = rhsEnd = NULL;
  2988. exprType tType = t_none;
  2989. bool numeric=false;
  2990. #ifdef WARNLEGACYCOMPARE
  2991. bool legacynumeric=false;
  2992. #endif
  2993. for (;;)
  2994. {
  2995. switch (*xpath) {
  2996. case '"':
  2997. case '\'':
  2998. if (quote)
  2999. {
  3000. if (*xpath == quote)
  3001. {
  3002. quote = 0;
  3003. quoteEnd = xpath;
  3004. }
  3005. }
  3006. else
  3007. {
  3008. if (quoteBegin)
  3009. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Quoted left hand side already seen");
  3010. quote = *xpath;
  3011. quoteBegin = xpath+1;
  3012. }
  3013. break;
  3014. case '[':
  3015. if (!quote)
  3016. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unclosed qualifier detected");
  3017. break;
  3018. case ']':
  3019. if (!quote)
  3020. {
  3021. if (!lhsEnd)
  3022. lhsEnd = xpath;
  3023. rhsEnd = xpath;
  3024. }
  3025. break;
  3026. case ' ':
  3027. case '\t':
  3028. if (!lhsEnd)
  3029. lhsEnd = xpath;
  3030. break;
  3031. case '!':
  3032. if (!quote)
  3033. {
  3034. if (tType)
  3035. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator xpath");
  3036. if ('=' != *(xpath+1))
  3037. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Invalid xpath qualifier expression in xpath");
  3038. if (!lhsEnd)
  3039. lhsEnd = xpath;
  3040. ++xpath;
  3041. tType = t_inequality;
  3042. wild = true; // true by default now, introduced ~ syntax, to denote wild string
  3043. }
  3044. break;
  3045. case '=':
  3046. if (!quote)
  3047. {
  3048. if (wild)
  3049. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Wildcard match '~' makes no sense in this context");
  3050. if (tType)
  3051. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator xpath");
  3052. tType = t_equality;
  3053. wild = true; // true by default now, introduced ~ syntax, to denote wild string
  3054. if (!lhsEnd)
  3055. lhsEnd = xpath;
  3056. }
  3057. break;
  3058. case '>':
  3059. if (!quote)
  3060. {
  3061. if (wild)
  3062. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Wildcard match '~' makes no sense in this context");
  3063. if (tType)
  3064. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator in xpath");
  3065. if (!lhsEnd)
  3066. lhsEnd = xpath;
  3067. #ifdef WARNLEGACYCOMPARE
  3068. legacynumeric = true;
  3069. #endif
  3070. if ('=' == *(xpath+1))
  3071. {
  3072. ++xpath;
  3073. tType = t_gteq;
  3074. }
  3075. else
  3076. tType = t_gt;
  3077. }
  3078. break;
  3079. case '<':
  3080. if (!quote)
  3081. {
  3082. if (tType)
  3083. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator in xpath");
  3084. if (!lhsEnd)
  3085. lhsEnd = xpath;
  3086. #ifdef WARNLEGACYCOMPARE
  3087. legacynumeric = true;
  3088. #endif
  3089. if ('=' == *(xpath+1))
  3090. {
  3091. ++xpath;
  3092. tType = t_lteq;
  3093. }
  3094. else
  3095. tType = t_lt;
  3096. }
  3097. break;
  3098. case '~':
  3099. if (!quote)
  3100. {
  3101. if (!tType)
  3102. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected wild operator in xpath");
  3103. wild = true;
  3104. }
  3105. break;
  3106. case '?':
  3107. if (!quote)
  3108. {
  3109. if (!tType)
  3110. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected case-insensitive operator in xpath");
  3111. nocase = true;
  3112. }
  3113. break;
  3114. case '\0':
  3115. rhsEnd = xpath;
  3116. break;
  3117. }
  3118. if (rhsEnd)
  3119. break;
  3120. xpath++;
  3121. if (!rhsBegin && tType && !isspace(*xpath))
  3122. rhsBegin = xpath;
  3123. }
  3124. if (quote)
  3125. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, unclosed quoted content");
  3126. if (tType)
  3127. {
  3128. if (quoteBegin && !quoteEnd)
  3129. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, RHS missing closing quote");
  3130. if (rhsBegin && !rhsEnd)
  3131. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, RHS missing closing quote");
  3132. if (!quoteBegin && rhsEnd) // validate it's a numeric
  3133. {
  3134. const char *c = rhsBegin;
  3135. for (;;)
  3136. {
  3137. if (!isdigit(*c++))
  3138. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, RHS is an unquoted string");
  3139. if (c==rhsEnd) break;
  3140. }
  3141. }
  3142. }
  3143. MAKE_LSTRING(lhs, start, lhsEnd-start);
  3144. bool ret = false;
  3145. const char *tProp = splitXPathX(lhs);
  3146. MAKE_LSTRING(head, lhs, tProp-lhs);
  3147. Owned<IPropertyTreeIterator> iter = getElements(head);
  3148. ForEach (*iter)
  3149. {
  3150. IPropertyTree &found = iter->query();
  3151. if (t_none == tType)
  3152. {
  3153. if (found.hasProp(tProp))
  3154. {
  3155. ret = true;
  3156. break;
  3157. }
  3158. }
  3159. else
  3160. {
  3161. Owned<IPropertyTreeIterator> _iter2;
  3162. IPropertyTreeIterator *iter2;
  3163. IPropertyTree *matchElem;
  3164. if (isAttribute(tProp))
  3165. {
  3166. matchElem = &found;
  3167. iter2 = NULL;
  3168. }
  3169. else
  3170. {
  3171. _iter2.setown(found.getElements(tProp));
  3172. iter2 = _iter2;
  3173. if (iter2->first())
  3174. matchElem = &iter2->query();
  3175. else
  3176. continue;
  3177. tProp = NULL;
  3178. }
  3179. for (;;)
  3180. {
  3181. if (matchElem->isBinary(tProp))
  3182. UNIMPLEMENTED;
  3183. const char *rhs;
  3184. unsigned rhslength;
  3185. if (quoteEnd)
  3186. {
  3187. rhs = quoteBegin;
  3188. rhslength = quoteEnd-quoteBegin;
  3189. #ifdef WARNLEGACYCOMPARE
  3190. if (legacynumeric)
  3191. {
  3192. if (isdigit(*rhs))
  3193. IWARNLOG("Possible deprecated use of quoted numeric comparison operation: %s", xxpath);
  3194. }
  3195. #endif
  3196. }
  3197. else if (rhsEnd)
  3198. {
  3199. rhs = rhsBegin;
  3200. rhslength = rhsEnd-rhsBegin;
  3201. numeric = true;
  3202. }
  3203. else
  3204. {
  3205. rhs = NULL;
  3206. rhslength = 0;
  3207. }
  3208. if (matchElem->isCompressed(tProp))
  3209. {
  3210. StringBuffer s;
  3211. matchElem->getProp(tProp, s);
  3212. ret = match(wild, numeric, xxpath, tType, s.str(), s.length(), rhs, rhslength, nocase);
  3213. }
  3214. else
  3215. {
  3216. const char *value = matchElem->queryProp(tProp);
  3217. if (value)
  3218. ret = match(wild, numeric, xxpath, tType, value, value?(size32_t)strlen(value):0, rhs, rhslength, nocase);
  3219. else if (tType == t_equality)
  3220. ret = (NULL == rhs || '\0' == *rhs);
  3221. else if (tType == t_inequality)
  3222. ret = (NULL != rhs && '\0' != *rhs);
  3223. }
  3224. if (ret)
  3225. break;
  3226. if (!iter2 || !iter2->next())
  3227. break;
  3228. matchElem = &iter2->query();
  3229. }
  3230. if (ret)
  3231. break;
  3232. }
  3233. }
  3234. xxpath = xpath;
  3235. return ret;
  3236. }
  3237. AttrValue *PTree::findAttribute(const char *key) const
  3238. {
  3239. if (attrs)
  3240. {
  3241. AttrValue *a = attrs+numAttrs;
  3242. if (isnocase())
  3243. {
  3244. while (a-- != attrs)
  3245. {
  3246. if (strieq(a->key.get(), key))
  3247. return a;
  3248. }
  3249. }
  3250. else
  3251. {
  3252. while (a-- != attrs)
  3253. {
  3254. if (streq(a->key.get(), key))
  3255. return a;
  3256. }
  3257. }
  3258. }
  3259. return nullptr;
  3260. }
  3261. const char *PTree::getAttributeValue(const char *key) const
  3262. {
  3263. AttrValue *e = findAttribute(key);
  3264. if (e)
  3265. return e->value.get();
  3266. return nullptr;
  3267. }
  3268. unsigned PTree::getAttributeCount() const
  3269. {
  3270. return numAttrs;
  3271. }
  3272. AttrValue *PTree::getNextAttribute(AttrValue *cur) const
  3273. {
  3274. if (0 == numAttrs)
  3275. return nullptr;
  3276. else if (nullptr == cur)
  3277. return attrs;
  3278. else
  3279. {
  3280. if (cur == (attrs+(numAttrs-1)))
  3281. return nullptr;
  3282. return ++cur;
  3283. }
  3284. }
  3285. //////////////////////
  3286. // LocalPTree
  3287. static RelaxedAtomic<unsigned> numLocalTrees;
  3288. unsigned queryNumLocalTrees()
  3289. {
  3290. return numLocalTrees;
  3291. }
  3292. LocalPTree::LocalPTree(const char *_name, byte _flags, IPTArrayValue *_value, ChildMap *_children) : PTree(_flags|ipt_fast, _value, _children)
  3293. {
  3294. if (_name)
  3295. setName(_name);
  3296. numLocalTrees++;
  3297. }
  3298. LocalPTree::~LocalPTree()
  3299. {
  3300. numLocalTrees--;
  3301. name.destroy();
  3302. if (!attrs)
  3303. return;
  3304. AttrValue *a = attrs+numAttrs;
  3305. while (a--!=attrs)
  3306. {
  3307. a->key.destroy();
  3308. a->value.destroy();
  3309. }
  3310. free(attrs);
  3311. }
  3312. const char *LocalPTree::queryName() const
  3313. {
  3314. return name.get();
  3315. }
  3316. void LocalPTree::setName(const char *_name)
  3317. {
  3318. if (_name==name.get())
  3319. return;
  3320. AttrStr *oname = name.getPtr(); // Don't free until after we copy - they could overlap
  3321. if (!name.set(_name))
  3322. name.setPtr(AttrStr::create(_name));
  3323. if (oname)
  3324. AttrStr::destroy(oname);
  3325. }
  3326. bool LocalPTree::removeAttribute(const char *key)
  3327. {
  3328. AttrValue *del = findAttribute(key);
  3329. if (!del)
  3330. return false;
  3331. if (arrayOwner)
  3332. {
  3333. CQualifierMap *map = arrayOwner->queryMap();
  3334. if (map)
  3335. map->removeEntryIfMapped(key, del->value.get(), this);
  3336. }
  3337. numAttrs--;
  3338. unsigned pos = del-attrs;
  3339. del->key.destroy();
  3340. del->value.destroy();
  3341. memmove(attrs+pos, attrs+pos+1, (numAttrs-pos)*sizeof(AttrValue));
  3342. return true;
  3343. }
  3344. void LocalPTree::setAttribute(const char *key, const char *val)
  3345. {
  3346. if (!key)
  3347. return;
  3348. if (!validateXMLTag(key+1))
  3349. throw MakeIPTException(-1, "Invalid xml attribute: %s", key);
  3350. if (!val)
  3351. val = ""; // cannot have NULL value
  3352. AttrValue *v = findAttribute(key);
  3353. AttrStr *goer = nullptr;
  3354. if (v)
  3355. {
  3356. if (streq(v->value.get(), val))
  3357. return;
  3358. goer = v->value.getPtr();
  3359. }
  3360. else
  3361. {
  3362. attrs = (AttrValue *)realloc(attrs, (numAttrs+1)*sizeof(AttrValue));
  3363. v = new(&attrs[numAttrs++]) AttrValue; // Initialize new AttrValue
  3364. if (!v->key.set(key))
  3365. v->key.setPtr(isnocase() ? AttrStr::createNC(key) : AttrStr::create(key));
  3366. }
  3367. if (arrayOwner)
  3368. {
  3369. CQualifierMap *map = arrayOwner->queryMap();
  3370. if (map)
  3371. {
  3372. if (goer)
  3373. map->replaceEntryIfMapped(key, v->value.get(), val, this);
  3374. else
  3375. map->insertEntryIfMapped(key, val, this);
  3376. }
  3377. }
  3378. if (!v->value.set(val))
  3379. v->value.setPtr(AttrStr::create(val));
  3380. if (goer)
  3381. AttrStr::destroy(goer);
  3382. }
  3383. #ifdef TRACE_STRING_SIZE
  3384. std::atomic<__int64> AttrStr::totsize { 0 };
  3385. std::atomic<__int64> AttrStr::maxsize { 0 };
  3386. #endif
  3387. #ifdef TRACE_ATOM_SIZE
  3388. std::atomic<__int64> AttrStrAtom::totsize { 0 };
  3389. std::atomic<__int64> AttrStrAtom::maxsize { 0 };
  3390. #endif
  3391. ///////////////////
  3392. static RelaxedAtomic<unsigned> numAtomTrees;
  3393. unsigned queryNumAtomTrees()
  3394. {
  3395. return numAtomTrees;
  3396. }
  3397. CAtomPTree::CAtomPTree(const char *_name, byte _flags, IPTArrayValue *_value, ChildMap *_children) : PTree(_flags|ipt_lowmem, _value, _children)
  3398. {
  3399. numAtomTrees++;
  3400. if (_name)
  3401. setName(_name);
  3402. }
  3403. CAtomPTree::~CAtomPTree()
  3404. {
  3405. numAtomTrees--;
  3406. bool nc = isnocase();
  3407. HashKeyElement *name_ptr = name.getPtr();
  3408. if (name_ptr)
  3409. {
  3410. AtomRefTable *kT = nc?keyTableNC:keyTable;
  3411. #ifdef TRACE_ATOM_SIZE
  3412. size_t gosize = sizeof(HashKeyElement)+strlen(name_ptr->get())+1;
  3413. if (kT->releaseKey(name_ptr))
  3414. AttrStrAtom::totsize -= gosize;
  3415. #else
  3416. kT->releaseKey(name_ptr);
  3417. #endif
  3418. }
  3419. if (!attrs)
  3420. return;
  3421. AttrValue *a = attrs+numAttrs;
  3422. {
  3423. CriticalBlock block(hashcrit);
  3424. while (a--!=attrs)
  3425. {
  3426. if (a->key.isPtr())
  3427. attrHT->removekey(a->key.getPtr(), nc);
  3428. if (a->value.isPtr())
  3429. attrHT->removeval(a->value.getPtr());
  3430. }
  3431. freeAttrArray(attrs, numAttrs);
  3432. }
  3433. }
  3434. void CAtomPTree::setName(const char *_name)
  3435. {
  3436. AtomRefTable *kT = isnocase()?keyTableNC:keyTable;
  3437. HashKeyElement *oname = name.getPtr(); // NOTE - don't release yet as could overlap source name
  3438. if (!_name)
  3439. name.setPtr(nullptr);
  3440. else
  3441. {
  3442. if (!validateXMLTag(_name))
  3443. throw MakeIPTException(PTreeExcpt_InvalidTagName, ": %s", _name);
  3444. if (!name.set(_name))
  3445. {
  3446. #ifdef TRACE_ALL_ATOM
  3447. DBGLOG("TRACE_ALL_ATOM: %s", _name);
  3448. #endif
  3449. #ifdef TRACE_ATOM_SIZE
  3450. bool didCreate;
  3451. name.setPtr(kT->queryCreate(_name, didCreate));
  3452. if (didCreate)
  3453. {
  3454. AttrStrAtom::totsize += sizeof(HashKeyElement)+strlen(_name)+1;
  3455. if (AttrStrAtom::totsize > AttrStrAtom::maxsize)
  3456. {
  3457. AttrStrAtom::maxsize.store(AttrStrAtom::totsize);
  3458. DBGLOG("TRACE_ATOM_SIZE: total size now %" I64F "d", AttrStrAtom::maxsize.load());
  3459. }
  3460. }
  3461. #else
  3462. name.setPtr(kT->queryCreate(_name));
  3463. #endif
  3464. }
  3465. }
  3466. if (oname)
  3467. {
  3468. #ifdef TRACE_ATOM_SIZE
  3469. size_t gosize = sizeof(HashKeyElement)+strlen(oname->get())+1;
  3470. if (kT->releaseKey(oname))
  3471. AttrStrAtom::totsize -= gosize;
  3472. #else
  3473. kT->releaseKey(oname);
  3474. #endif
  3475. }
  3476. }
  3477. const char *CAtomPTree::queryName() const
  3478. {
  3479. return name.get();
  3480. }
  3481. unsigned CAtomPTree::queryHash() const
  3482. {
  3483. if (name.isPtr())
  3484. {
  3485. assert(name.getPtr());
  3486. return name.getPtr()->queryHash();
  3487. }
  3488. else
  3489. {
  3490. const char *_name = name.get();
  3491. size32_t nl = strlen(_name);
  3492. return isnocase() ? hashnc((const byte *) _name, nl, 0): hashc((const byte *) _name, nl, 0);
  3493. }
  3494. }
  3495. AttrValue *CAtomPTree::newAttrArray(unsigned n)
  3496. {
  3497. // NB crit must be locked
  3498. if (!n)
  3499. return nullptr;
  3500. if (freelistmax<=n)
  3501. {
  3502. freelist = (AttrValue **)realloc(freelist, sizeof(AttrValue *)*(n+1));
  3503. while (freelistmax<=n)
  3504. freelist[freelistmax++] = nullptr;
  3505. }
  3506. AttrValue *&p = freelist[n];
  3507. AttrValue *ret = p;
  3508. if (ret)
  3509. p = *(AttrValue **)ret;
  3510. else
  3511. ret = (AttrValue *)freeallocator.alloc(sizeof(AttrValue)*n);
  3512. return ret;
  3513. }
  3514. void CAtomPTree::freeAttrArray(AttrValue *a, unsigned n)
  3515. {
  3516. // NB crit must be locked
  3517. if (a)
  3518. {
  3519. AttrValue *&p = freelist[n];
  3520. *(AttrValue **)a = p;
  3521. p = a;
  3522. }
  3523. }
  3524. void CAtomPTree::setAttribute(const char *key, const char *val)
  3525. {
  3526. if (!key)
  3527. return;
  3528. if (!validateXMLTag(key+1))
  3529. throw MakeIPTException(-1, "Invalid xml attribute: %s", key);
  3530. if (!val)
  3531. val = ""; // cannot have NULL value
  3532. AttrValue *v = findAttribute(key);
  3533. if (v)
  3534. {
  3535. if (streq(v->value.get(), val))
  3536. return;
  3537. if (arrayOwner)
  3538. {
  3539. CQualifierMap *map = arrayOwner->queryMap();
  3540. if (map)
  3541. map->replaceEntryIfMapped(key, v->value.get(), val, this);
  3542. }
  3543. AttrStr * goer = v->value.getPtr();
  3544. if (!v->value.set(val))
  3545. {
  3546. CriticalBlock block(hashcrit);
  3547. if (goer)
  3548. attrHT->removeval(goer);
  3549. v->value.setPtr(attrHT->addval(val));
  3550. }
  3551. else if (goer)
  3552. {
  3553. CriticalBlock block(hashcrit);
  3554. attrHT->removeval(goer);
  3555. }
  3556. }
  3557. else
  3558. {
  3559. CriticalBlock block(hashcrit);
  3560. AttrValue *newattrs = newAttrArray(numAttrs+1);
  3561. if (attrs)
  3562. {
  3563. memcpy(newattrs, attrs, numAttrs*sizeof(AttrValue));
  3564. freeAttrArray(attrs, numAttrs);
  3565. }
  3566. if (arrayOwner)
  3567. {
  3568. CQualifierMap *map = arrayOwner->queryMap();
  3569. if (map)
  3570. map->insertEntryIfMapped(key, val, this);
  3571. }
  3572. v = &newattrs[numAttrs];
  3573. if (!v->key.set(key))
  3574. v->key.setPtr(attrHT->addkey(key, isnocase()));
  3575. if (!v->value.set(val))
  3576. v->value.setPtr(attrHT->addval(val));
  3577. numAttrs++;
  3578. attrs = newattrs;
  3579. }
  3580. }
  3581. bool CAtomPTree::removeAttribute(const char *key)
  3582. {
  3583. AttrValue *del = findAttribute(key);
  3584. if (!del)
  3585. return false;
  3586. numAttrs--;
  3587. if (arrayOwner)
  3588. {
  3589. CQualifierMap *map = arrayOwner->queryMap();
  3590. if (map)
  3591. map->removeEntryIfMapped(key, del->value.get(), this);
  3592. }
  3593. CriticalBlock block(hashcrit);
  3594. if (del->key.isPtr())
  3595. attrHT->removekey(del->key.getPtr(), isnocase());
  3596. if (del->value.isPtr())
  3597. attrHT->removeval(del->value.getPtr());
  3598. AttrValue *newattrs = newAttrArray(numAttrs);
  3599. if (newattrs)
  3600. {
  3601. unsigned pos = del-attrs;
  3602. memcpy(newattrs, attrs, pos*sizeof(AttrValue));
  3603. memcpy(newattrs+pos, attrs+pos+1, (numAttrs-pos)*sizeof(AttrValue));
  3604. }
  3605. freeAttrArray(attrs, numAttrs+1);
  3606. attrs = newattrs;
  3607. return true;
  3608. }
  3609. ///////////////////
  3610. bool isEmptyPTree(IPropertyTree *t)
  3611. {
  3612. if (!t)
  3613. return true;
  3614. if (t->numUniq())
  3615. return false;
  3616. Owned<IAttributeIterator> ai = t->getAttributes();
  3617. if (ai->first())
  3618. return false;
  3619. const char *s = t->queryProp(NULL);
  3620. if (s&&*s)
  3621. return false;
  3622. return true;
  3623. }
  3624. ///////////////////
  3625. PTLocalIteratorBase::PTLocalIteratorBase(const PTree *_tree, const char *_id, bool _nocase, bool _sort) : nocase(_nocase), sort(_sort), id(_id), tree(_tree)
  3626. {
  3627. class CPTArrayIterator : public ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>
  3628. {
  3629. public:
  3630. CPTArrayIterator(IPropertyTreeIterator &src) : ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>(elems)
  3631. {
  3632. ForEach(src)
  3633. elems.append(src.get());
  3634. elems.sort(comparePropTrees);
  3635. }
  3636. IArrayOf<IPropertyTree> elems;
  3637. };
  3638. tree->Link();
  3639. baseIter = tree->checkChildren()->getIterator(sort);
  3640. iter = NULL;
  3641. current = NULL;
  3642. }
  3643. PTLocalIteratorBase::~PTLocalIteratorBase()
  3644. {
  3645. baseIter->Release();
  3646. ::Release(iter);
  3647. tree->Release();
  3648. }
  3649. // IPropertyTreeIterator
  3650. bool PTLocalIteratorBase::first()
  3651. {
  3652. ::Release(iter); iter=NULL;
  3653. if (!baseIter || !baseIter->first()) return false;
  3654. return _next();
  3655. }
  3656. bool PTLocalIteratorBase::_next()
  3657. {
  3658. if (iter && iter->isValid() && iter->next())
  3659. return true;
  3660. for (;;)
  3661. {
  3662. for (;;)
  3663. {
  3664. if (!baseIter->isValid())
  3665. {
  3666. current = NULL;
  3667. return false;
  3668. }
  3669. else if (match())
  3670. break;
  3671. baseIter->next();
  3672. }
  3673. IPropertyTree *element = &baseIter->query();
  3674. baseIter->next();
  3675. if (iter)
  3676. iter->Release();
  3677. iter = element->getElements(NULL);
  3678. if (iter->first())
  3679. {
  3680. current = &iter->query();
  3681. return true;
  3682. }
  3683. }
  3684. }
  3685. bool PTLocalIteratorBase::next()
  3686. {
  3687. return _next();
  3688. }
  3689. bool PTLocalIteratorBase::isValid()
  3690. {
  3691. return (current != NULL);
  3692. }
  3693. /////////////////////////////
  3694. bool PTIdMatchIterator::match()
  3695. {
  3696. IPropertyTree &tree = baseIter->query();
  3697. const char *key = tree.queryName();
  3698. return (0 != WildMatch(key, id, nocase));
  3699. }
  3700. ////////////////////////////
  3701. SingleIdIterator::SingleIdIterator(const PTree &_tree, unsigned pos, unsigned _many) : many(_many), count(0), whichNext(pos-1), start(pos-1), current(NULL), tree(_tree)
  3702. {
  3703. tree.Link();
  3704. }
  3705. SingleIdIterator::~SingleIdIterator()
  3706. {
  3707. tree.Release();
  3708. }
  3709. void SingleIdIterator::setCurrent(unsigned pos)
  3710. {
  3711. current = tree.value->queryElement(pos);
  3712. }
  3713. // IInterface impl.
  3714. bool SingleIdIterator::first()
  3715. {
  3716. whichNext = start;
  3717. if (!tree.value || !tree.value->isArray())
  3718. {
  3719. if (0 == whichNext)
  3720. {
  3721. current = const_cast<PTree*>(&tree);
  3722. count = 1;
  3723. }
  3724. }
  3725. else
  3726. {
  3727. count = tree.value->elements();
  3728. if (whichNext < count)
  3729. setCurrent(whichNext);
  3730. else
  3731. return false;
  3732. }
  3733. ++whichNext;
  3734. return true;
  3735. }
  3736. bool SingleIdIterator::next()
  3737. {
  3738. if ((whichNext>=count) || ((unsigned) -1 != many && whichNext>start+many))
  3739. {
  3740. current = NULL;
  3741. return false;
  3742. }
  3743. setCurrent(whichNext++);
  3744. return true;
  3745. }
  3746. bool SingleIdIterator::isValid()
  3747. {
  3748. return (NULL != current);
  3749. }
  3750. //////////////
  3751. class StackElement
  3752. {
  3753. public:
  3754. void init(IPropertyTreeIterator *_iter, const char *_xpath)
  3755. {
  3756. xpath = (char *)strdup(_xpath);
  3757. iter=LINK(_iter);
  3758. }
  3759. void clear()
  3760. {
  3761. ::Release(iter);
  3762. if (xpath)
  3763. free(xpath);
  3764. }
  3765. IPropertyTreeIterator *get(StringAttr &str)
  3766. {
  3767. str.setown(xpath); return iter; // NB used in place of pop, as element invalid after call
  3768. }
  3769. IPropertyTreeIterator *iter;
  3770. char * xpath;
  3771. };
  3772. ///////////////////
  3773. PTStackIterator::PTStackIterator(IPropertyTreeIterator *_iter, const char *_xpath) : rootIter(_iter), xpath(_xpath)
  3774. {
  3775. iter = NULL;
  3776. xxpath = "";
  3777. current = NULL;
  3778. stacklen = 0;
  3779. stackmax = 4;
  3780. stack = (StackElement *)malloc(sizeof(StackElement)*stackmax);
  3781. }
  3782. PTStackIterator::~PTStackIterator()
  3783. {
  3784. while (stacklen)
  3785. stack[--stacklen].clear();
  3786. ::Release(iter);
  3787. ::Release(rootIter);
  3788. free(stack);
  3789. }
  3790. void PTStackIterator::setIterator(IPropertyTreeIterator *_iter)
  3791. {
  3792. assertex(_iter);
  3793. if (iter)
  3794. iter->Release();
  3795. iter = _iter;
  3796. iter->first();
  3797. }
  3798. // IIterator impl.
  3799. bool PTStackIterator::first()
  3800. {
  3801. while (stacklen)
  3802. stack[--stacklen].clear();
  3803. current = NULL;
  3804. xxpath = xpath;
  3805. rootIter->Link();
  3806. setIterator(rootIter);
  3807. return next();
  3808. }
  3809. bool PTStackIterator::isValid()
  3810. {
  3811. return (current != NULL);
  3812. }
  3813. IPropertyTree &PTStackIterator::query()
  3814. {
  3815. assertex(current);
  3816. return *current;
  3817. }
  3818. bool PTStackIterator::next()
  3819. {
  3820. bool separator = false;
  3821. if (iter)
  3822. {
  3823. IPropertyTree *element = NULL;
  3824. StringBuffer qualifierText;
  3825. for (;;)
  3826. {
  3827. while (!iter->isValid())
  3828. {
  3829. if (iter) iter->Release();
  3830. iter = popFromStack(stackPath); // leaves linked
  3831. if (!iter)
  3832. {
  3833. current = NULL;
  3834. return false;
  3835. }
  3836. xxpath = stackPath;
  3837. element = NULL;
  3838. }
  3839. if (!element)
  3840. {
  3841. element = &iter->query();
  3842. iter->next();
  3843. }
  3844. while (element)
  3845. {
  3846. switch (*xxpath)
  3847. {
  3848. case '\0':
  3849. current = element;
  3850. return true;
  3851. case '.':
  3852. if (separator) throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Syntax error");
  3853. separator=false;
  3854. ++xxpath;
  3855. if (*xpath && '/' != *xpath)
  3856. throw MakeXPathException(xpath-1, PTreeExcpt_XPath_Unsupported, 0, "\"/\" expected");
  3857. break;
  3858. case '/':
  3859. ++xxpath;
  3860. if ('/' == *xxpath)
  3861. {
  3862. --xxpath;
  3863. if (iter->isValid())
  3864. pushToStack(iter, xxpath);
  3865. setIterator(element->getElements(xxpath));
  3866. xxpath = "";
  3867. element = NULL;
  3868. }
  3869. separator=true;
  3870. break;
  3871. default:
  3872. separator=false;
  3873. if (iter->isValid())
  3874. pushToStack(iter, xxpath);
  3875. bool wild, numeric;
  3876. const char *start = xxpath;
  3877. readWildIdIndex(xxpath, wild, numeric);
  3878. size32_t s = xxpath-start;
  3879. if (s)
  3880. {
  3881. // NB: actually an id not qualifier, just sharing var.
  3882. qualifierText.clear().append(s, start);
  3883. bool mapped = false;
  3884. if (!wild && !numeric)
  3885. {
  3886. ChildMap *children = ((PTree *)element)->checkChildren();
  3887. if (children)
  3888. {
  3889. IPropertyTree *child = children->query(qualifierText);
  3890. if (child)
  3891. {
  3892. if ('[' == *xxpath)
  3893. {
  3894. const char *newXXPath = xxpath+1;
  3895. Owned<IPropertyTreeIterator> mapIter = checkMapIterator(newXXPath, *child);
  3896. if (mapIter)
  3897. {
  3898. setIterator(mapIter.getClear());
  3899. mapped = true;
  3900. xxpath = newXXPath;
  3901. }
  3902. }
  3903. }
  3904. }
  3905. }
  3906. if (!mapped)
  3907. setIterator(element->getElements(qualifierText));
  3908. }
  3909. else // must be qualifier.
  3910. {
  3911. if ('[' != *xxpath)
  3912. throw MakeXPathException(xxpath, PTreeExcpt_XPath_ParseError, 0, "Qualifier expected e.g. [..]");
  3913. const char *start = xxpath;
  3914. char quote = 0;
  3915. while (']' != *(++xxpath) || quote)
  3916. {
  3917. switch (*xxpath) {
  3918. case '\"':
  3919. case '\'':
  3920. {
  3921. if (quote)
  3922. {
  3923. if (*xxpath == quote)
  3924. quote = 0;
  3925. }
  3926. else
  3927. quote = *xxpath;
  3928. break;
  3929. }
  3930. case '\0':
  3931. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xxpath-start, "Qualifier brace unclosed");
  3932. }
  3933. }
  3934. ++xxpath;
  3935. qualifierText.clear().append(xxpath-start, start);
  3936. setIterator(element->getElements(qualifierText.str()));
  3937. }
  3938. element = NULL;
  3939. break;
  3940. }
  3941. }
  3942. }
  3943. }
  3944. return false;
  3945. }
  3946. void PTStackIterator::pushToStack(IPropertyTreeIterator *iter, const char *xpath)
  3947. {
  3948. if (stacklen==stackmax) {
  3949. stackmax *= 2;
  3950. stack = (StackElement *)realloc(stack, sizeof(StackElement)*stackmax);
  3951. }
  3952. stack[stacklen++].init(iter, xpath);
  3953. }
  3954. IPropertyTreeIterator *PTStackIterator::popFromStack(StringAttr &path)
  3955. {
  3956. if (!stacklen)
  3957. return NULL;
  3958. return stack[--stacklen].get(path);
  3959. }
  3960. #define DEFAULT_PTREE_TYPE LocalPTree
  3961. // factory methods
  3962. IPropertyTree *createPTree(MemoryBuffer &src, byte flags)
  3963. {
  3964. IPropertyTree *tree = createPTree(nullptr, flags);
  3965. tree->deserialize(src);
  3966. return tree;
  3967. }
  3968. IPropertyTree *createPTreeFromIPT(const IPropertyTree *srcTree, ipt_flags flags)
  3969. {
  3970. Owned<PTree> tree = (PTree *)createPTree(NULL, flags);
  3971. return tree->clone(*srcTree->queryBranch(NULL));
  3972. }
  3973. void mergePTree(IPropertyTree *target, IPropertyTree *toMerge)
  3974. {
  3975. Owned<IAttributeIterator> aiter = toMerge->getAttributes();
  3976. ForEach (*aiter)
  3977. target->addProp(aiter->queryName(), aiter->queryValue());
  3978. Owned<IPropertyTreeIterator> iter = toMerge->getElements("*");
  3979. ForEach (*iter)
  3980. {
  3981. IPropertyTree &e = iter->query();
  3982. target->addPropTree(e.queryName(), LINK(&e));
  3983. }
  3984. }
  3985. void _synchronizePTree(IPropertyTree *target, IPropertyTree *source, bool removeTargetsNotInSource)
  3986. {
  3987. Owned<IAttributeIterator> aiter = target->getAttributes();
  3988. StringArray targetAttrs;
  3989. ForEach (*aiter)
  3990. targetAttrs.append(aiter->queryName());
  3991. aiter.setown(source->getAttributes());
  3992. ForEach (*aiter)
  3993. {
  3994. const char *attr = aiter->queryName();
  3995. if (!target->hasProp(attr))
  3996. target->setProp(attr, aiter->queryValue());
  3997. else
  3998. {
  3999. const char *sValue = aiter->queryValue();
  4000. const char *tValue = target->queryProp(attr);
  4001. if (NULL == sValue)
  4002. {
  4003. if (NULL != tValue)
  4004. target->setProp(attr, sValue);
  4005. }
  4006. else if (NULL == tValue ||0 != strcmp(sValue, tValue))
  4007. target->setProp(attr, sValue);
  4008. targetAttrs.zap(attr);
  4009. }
  4010. }
  4011. if (removeTargetsNotInSource)
  4012. {
  4013. // remaining
  4014. ForEachItemIn (a, targetAttrs)
  4015. target->removeProp(targetAttrs.item(a));
  4016. }
  4017. bool equal = true;
  4018. MemoryBuffer srcMb;
  4019. const char *src = NULL;
  4020. if (target->isBinary())
  4021. {
  4022. MemoryBuffer tgtMb;
  4023. target->getPropBin(NULL, tgtMb);
  4024. source->getPropBin(NULL, srcMb);
  4025. if (tgtMb.length() != srcMb.length())
  4026. equal = false;
  4027. else if (0 != memcmp(tgtMb.toByteArray(), srcMb.toByteArray(), tgtMb.length()))
  4028. equal = false;
  4029. }
  4030. else
  4031. {
  4032. const char *tgt = target->queryProp(NULL);
  4033. src = source->queryProp(NULL);
  4034. unsigned lTgt = tgt?(size32_t)strlen(tgt):0;
  4035. unsigned lSrc = src?(size32_t)strlen(src):0;
  4036. if (lTgt != lSrc)
  4037. equal = false;
  4038. else if (0 != lTgt && (0 != strcmp(tgt, src)))
  4039. equal = false;
  4040. }
  4041. if (!equal)
  4042. {
  4043. if (target->isBinary())
  4044. target->setPropBin(NULL, srcMb.length(), srcMb.toByteArray());
  4045. else
  4046. target->setProp(NULL, src);
  4047. }
  4048. ICopyArrayOf<IPropertyTree> toProcess;
  4049. Owned<IPropertyTreeIterator> iter = source->getElements("*");
  4050. ForEach (*iter)
  4051. toProcess.append(iter->query());
  4052. iter.setown(target->getElements("*"));
  4053. ICopyArrayOf<IPropertyTree> removeTreeList;
  4054. Owned<IPropertyTreeIterator> srcTypeIter;
  4055. StringAttr firstOfType;
  4056. ForEach (*iter)
  4057. {
  4058. IPropertyTree &e = iter->query();
  4059. const char *name = e.queryName();
  4060. IPropertyTree *sourceCompare;
  4061. if (!source->hasProp(name))
  4062. {
  4063. removeTreeList.append(e);
  4064. firstOfType.clear();
  4065. srcTypeIter.clear();
  4066. }
  4067. else
  4068. {
  4069. if (firstOfType.isEmpty() || 0 != strcmp(firstOfType, e.queryName()))
  4070. {
  4071. if (firstOfType.length() && srcTypeIter)
  4072. {
  4073. // add remaining
  4074. while (srcTypeIter->next())
  4075. {
  4076. sourceCompare = &srcTypeIter->query();
  4077. target->addPropTree(sourceCompare->queryName(), LINK(sourceCompare));
  4078. toProcess.zap(*sourceCompare);
  4079. }
  4080. }
  4081. srcTypeIter.setown(source->getElements(e.queryName()));
  4082. firstOfType.set(e.queryName());
  4083. assertex(srcTypeIter->first());
  4084. sourceCompare = &srcTypeIter->query();
  4085. }
  4086. else // 2nd of type etc..
  4087. sourceCompare = srcTypeIter->next() ? &srcTypeIter->query() : NULL;
  4088. if (sourceCompare)
  4089. {
  4090. toProcess.zap(*sourceCompare);
  4091. _synchronizePTree(&e, sourceCompare, removeTargetsNotInSource);
  4092. }
  4093. else
  4094. removeTreeList.append(e);
  4095. }
  4096. }
  4097. if (removeTargetsNotInSource)
  4098. {
  4099. ForEachItemIn (rt, removeTreeList)
  4100. target->removeTree(&removeTreeList.item(rt));
  4101. }
  4102. // add unprocessed source elements, not reference by name in target
  4103. ForEachItemIn (s, toProcess)
  4104. {
  4105. IPropertyTree &e = toProcess.item(s);
  4106. target->addPropTree(e.queryName(), LINK(&e));
  4107. }
  4108. }
  4109. /* ensure target is equivalent to source whilst retaining elements already present in target.
  4110. * presevers ordering of matching elements.
  4111. * If removeTargetsNotInSource = true (default) elements in the target not present in the source will be removed
  4112. */
  4113. void synchronizePTree(IPropertyTree *target, IPropertyTree *source, bool removeTargetsNotInSource, bool rootsMustMatch)
  4114. {
  4115. if (rootsMustMatch)
  4116. {
  4117. const char *srcName = source->queryName();
  4118. const char *tgtName = target->queryName();
  4119. if (0 != strcmp(srcName, tgtName))
  4120. throw MakeIPTException(PTreeExcpt_Unsupported, "Cannot synchronize if root nodes mismatch");
  4121. }
  4122. _synchronizePTree(target, source, removeTargetsNotInSource);
  4123. }
  4124. IPropertyTree *ensurePTree(IPropertyTree *root, const char *xpath)
  4125. {
  4126. return createPropBranch(root, xpath, true);
  4127. }
  4128. IPTreeReadException *createPTreeReadException(int code, const char *msg, const char *context, unsigned line, offset_t offset)
  4129. {
  4130. //Do not use jlib_thrown_decl because it causes problems with VS2017 - I think because of beforeDispose() in CInterfaceOf.
  4131. //The type of the object actually thrown is IPTreeReadException which does have a jlib_thrown_decl - so it will still be caught.
  4132. class CPTreeReadException : implements CInterfaceOf<IPTreeReadException>
  4133. {
  4134. int code;
  4135. StringAttr msg;
  4136. StringAttr context;
  4137. unsigned line;
  4138. offset_t offset;
  4139. StringBuffer &getErrorMessage(StringBuffer &out) const
  4140. {
  4141. switch (code)
  4142. {
  4143. case PTreeRead_EOS:
  4144. return out.append("Error - end of stream");
  4145. case PTreeRead_syntax:
  4146. return out.append("Error - syntax error");
  4147. }
  4148. return out;
  4149. }
  4150. public:
  4151. CPTreeReadException(int _code, const char *_msg, const char *_context, unsigned _line, offset_t _offset) : code(_code), msg(_msg), context(_context), line(_line), offset(_offset) { }
  4152. // IException
  4153. int errorCode() const { return code; }
  4154. StringBuffer &errorMessage(StringBuffer &str) const
  4155. {
  4156. getErrorMessage(str);
  4157. if (msg.length())
  4158. str.append(" \"").append(msg).append("\"");
  4159. str.append(" [");
  4160. if (line>1) // don't bother with line 1, there may be no line breaks.
  4161. str.append("line ").append(line).append(", ");
  4162. str.append("file offset ").append(offset).append("]");
  4163. if (context.length())
  4164. str.newline().append(context);
  4165. return str;
  4166. }
  4167. MessageAudience errorAudience() const { return MSGAUD_user; }
  4168. const char *queryDescription() { return msg; }
  4169. unsigned queryLine() { return line; }
  4170. offset_t queryOffset() { return offset; }
  4171. const char *queryContext() { return context.get(); }
  4172. };
  4173. return new CPTreeReadException(code, msg, context, line, offset);
  4174. }
  4175. template <typename T>
  4176. class CommonReaderBase : public CInterface
  4177. {
  4178. Linked<ISimpleReadStream> lstream;
  4179. ISimpleReadStream *stream;
  4180. bool bufOwned, nullTerm;
  4181. byte *buf, *bufPtr;
  4182. size32_t bufSize, bufRemaining;
  4183. protected:
  4184. PTreeReaderOptions readerOptions;
  4185. bool ignoreWhiteSpace, noRoot;
  4186. Linked<IPTreeNotifyEvent> iEvent;
  4187. offset_t curOffset;
  4188. unsigned line;
  4189. char nextChar;
  4190. private:
  4191. void init()
  4192. {
  4193. ignoreWhiteSpace = 0 != ((unsigned)readerOptions & (unsigned)ptr_ignoreWhiteSpace);
  4194. noRoot = 0 != ((unsigned)readerOptions & (unsigned)ptr_noRoot);
  4195. }
  4196. void resetState()
  4197. {
  4198. bufPtr = buf;
  4199. nextChar = 0;
  4200. if (nullTerm || stream)
  4201. bufRemaining = 0;
  4202. curOffset = 0;
  4203. line = 0;
  4204. }
  4205. public:
  4206. CommonReaderBase(ISimpleReadStream &_stream, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions, size32_t _bufSize=0) :
  4207. bufSize(_bufSize), readerOptions(_readerOptions), iEvent(&_iEvent)
  4208. {
  4209. if (!bufSize) bufSize = 0x8000;
  4210. buf = new byte[bufSize];
  4211. bufRemaining = 0;
  4212. curOffset = 0;
  4213. bufOwned = true;
  4214. nullTerm = false;
  4215. lstream.set(&_stream);
  4216. stream = &_stream; // for efficiency
  4217. init();
  4218. resetState();
  4219. }
  4220. CommonReaderBase(const void *_buf, size32_t bufLength, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
  4221. readerOptions(_readerOptions), iEvent(&_iEvent)
  4222. {
  4223. bufSize = 0; // not used for direct reads
  4224. stream = NULL; // not used for direct reads
  4225. bufRemaining = bufLength;
  4226. nullTerm = false;
  4227. buf = (byte *)_buf;
  4228. bufOwned = false;
  4229. init();
  4230. resetState();
  4231. }
  4232. CommonReaderBase(const void *_buf, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
  4233. readerOptions(_readerOptions), iEvent(&_iEvent)
  4234. {
  4235. bufSize = 0; // not used for direct reads
  4236. stream = NULL; // not used for direct reads
  4237. curOffset = 0;
  4238. bufRemaining = 0;
  4239. nullTerm = true;
  4240. buf = (byte *)_buf;
  4241. bufOwned = false;
  4242. init();
  4243. resetState();
  4244. }
  4245. ~CommonReaderBase()
  4246. {
  4247. if (bufOwned)
  4248. delete [] buf;
  4249. }
  4250. protected:
  4251. virtual void reset()
  4252. {
  4253. resetState();
  4254. }
  4255. void rewind(size32_t n)
  4256. {
  4257. assertex(curOffset >= n);
  4258. if (!n) return;
  4259. curOffset -= n;
  4260. size32_t d = (size32_t)(bufPtr-buf);
  4261. if (n > d) n = d;
  4262. if (!nullTerm)
  4263. bufRemaining += n;
  4264. for (;;)
  4265. {
  4266. --bufPtr;
  4267. if (!--n) break;
  4268. if (10 == *bufPtr) --line;
  4269. }
  4270. }
  4271. bool checkBOM()
  4272. {
  4273. bool utf16 = false;
  4274. bool utf8 = false;
  4275. // Note - technically the utf16 LE case could also be utf32 LE (utf32 BE would be 0x00 0x00 0xfe 0xff)
  4276. // But utf32 is so rare that we ignore it for now
  4277. switch ((unsigned char)nextChar)
  4278. {
  4279. case 0xff:
  4280. readNext();
  4281. if (0xfe == (unsigned char)nextChar)
  4282. utf16 = true;
  4283. break;
  4284. case 0xfe:
  4285. readNext();
  4286. if (0xff == (unsigned char)nextChar)
  4287. utf16 = true;
  4288. break;
  4289. case 0xef:
  4290. readNext();
  4291. if (0xbb == (unsigned char)nextChar)
  4292. {
  4293. readNext();
  4294. if (0xbf == (unsigned char)nextChar)
  4295. utf8 = true;
  4296. }
  4297. break;
  4298. default:
  4299. break;
  4300. }
  4301. if (utf8)
  4302. return true;
  4303. else if (utf16)
  4304. error("Unsupported utf16 format detected in BOM header", false);
  4305. return false;
  4306. }
  4307. inline void expecting(const char *str)
  4308. {
  4309. StringBuffer errorMsg("Expecting \"");
  4310. error(errorMsg.append(str).append("\"").str());
  4311. }
  4312. inline void eos()
  4313. {
  4314. error("String terminator hit");
  4315. }
  4316. void match(const char *txt, const char *msg=NULL)
  4317. {
  4318. const char *c = txt;
  4319. for (;;)
  4320. {
  4321. if (*c == '\0') break;
  4322. readNext();
  4323. if (toupper(nextChar) != toupper(*c))
  4324. {
  4325. if (msg)
  4326. error(msg);
  4327. throw c;
  4328. }
  4329. c++;
  4330. }
  4331. }
  4332. void error(const char *msg=NULL, bool giveContext=true, PTreeReadExcptCode code=PTreeRead_syntax) __attribute__((noreturn))
  4333. {
  4334. StringBuffer context;
  4335. if (giveContext)
  4336. {
  4337. size32_t bufPos = (size32_t)(bufPtr-buf);
  4338. unsigned preLen = std::min(40U, bufPos);
  4339. size32_t bR = bufRemaining;
  4340. if (nullTerm)
  4341. {
  4342. byte *tPtr = bufPtr;
  4343. while (bR<40)
  4344. {
  4345. if ('\0' == *tPtr++) break;
  4346. bR++;
  4347. }
  4348. }
  4349. unsigned postLen = std::min(80-preLen, bR);
  4350. const char *bufferContext = (const char *)(bufPtr - preLen);
  4351. context.append(preLen, bufferContext);
  4352. context.append("*ERROR*");
  4353. context.append(postLen, bufferContext+preLen);
  4354. }
  4355. throw createPTreeReadException(code, msg, context.str(), line+1, curOffset);
  4356. }
  4357. inline void readNext()
  4358. {
  4359. if (!readNextToken())
  4360. error("End of stream encountered whilst parsing", true, PTreeRead_EOS);
  4361. curOffset++;
  4362. }
  4363. inline bool checkReadNext()
  4364. {
  4365. if (!readNextToken())
  4366. return false;
  4367. curOffset++;
  4368. return true;
  4369. }
  4370. inline bool checkStartReadNext()
  4371. {
  4372. if (curOffset || nextChar) //not at starting state
  4373. return true;
  4374. return readNextToken();
  4375. }
  4376. inline bool readNextToken();
  4377. inline bool checkSkipWS()
  4378. {
  4379. while (isspace(nextChar)) if (!checkReadNext()) return false;
  4380. return true;
  4381. }
  4382. inline void skipWS()
  4383. {
  4384. while (isspace(nextChar)) readNext();
  4385. }
  4386. };
  4387. class CInstStreamReader { public: }; // only used to ensure different template definitions.
  4388. class CInstBufferReader { public: };
  4389. class CInstStringReader { public: };
  4390. template <> inline bool CommonReaderBase<CInstStreamReader>::readNextToken()
  4391. {
  4392. // do own buffering, to have reasonable error context.
  4393. if (0 == bufRemaining)
  4394. {
  4395. size32_t _bufRemaining = stream->read(bufSize, buf);
  4396. if (!_bufRemaining)
  4397. return false;
  4398. bufRemaining = _bufRemaining;
  4399. bufPtr = buf;
  4400. }
  4401. --bufRemaining;
  4402. nextChar = *bufPtr++;
  4403. if (10 == nextChar)
  4404. line++;
  4405. return true;
  4406. }
  4407. template <> inline bool CommonReaderBase<CInstBufferReader>::readNextToken()
  4408. {
  4409. if (0 == bufRemaining)
  4410. return false;
  4411. --bufRemaining;
  4412. nextChar = *bufPtr++;
  4413. if (10 == nextChar)
  4414. line++;
  4415. return true;
  4416. }
  4417. template <> inline bool CommonReaderBase<CInstStringReader>::readNextToken()
  4418. {
  4419. nextChar = *bufPtr++;
  4420. if ('\0' == nextChar)
  4421. {
  4422. --bufPtr;
  4423. return false;
  4424. }
  4425. if (10 == nextChar)
  4426. line++;
  4427. return true;
  4428. }
  4429. template <typename X>
  4430. class CXMLReaderBase : public CommonReaderBase<X>, implements IEntityHelper
  4431. {
  4432. StringAttrMapping entityTable;
  4433. protected:
  4434. bool ignoreNameSpaces;
  4435. bool hadXMLDecl;
  4436. private:
  4437. void init()
  4438. {
  4439. ignoreNameSpaces = 0 != ((unsigned) readerOptions & (unsigned)ptr_ignoreNameSpaces);
  4440. }
  4441. void resetState()
  4442. {
  4443. hadXMLDecl = false;
  4444. }
  4445. public:
  4446. typedef CommonReaderBase<X> PARENT;
  4447. using PARENT::nextChar;
  4448. using PARENT::readNext;
  4449. using PARENT::expecting;
  4450. using PARENT::match;
  4451. using PARENT::error;
  4452. using PARENT::skipWS;
  4453. using PARENT::rewind;
  4454. using PARENT::readerOptions;
  4455. CXMLReaderBase(ISimpleReadStream &_stream, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _xmlReaderOptions, size32_t _bufSize=0)
  4456. : CommonReaderBase<X>(_stream, _iEvent, _xmlReaderOptions, _bufSize)
  4457. {
  4458. init();
  4459. resetState();
  4460. }
  4461. CXMLReaderBase(const void *_buf, size32_t bufLength, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _xmlReaderOptions)
  4462. : CommonReaderBase<X>(_buf, bufLength, _iEvent, _xmlReaderOptions)
  4463. {
  4464. init();
  4465. resetState();
  4466. }
  4467. CXMLReaderBase(const void *_buf, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _xmlReaderOptions)
  4468. : CommonReaderBase<X>(_buf, _iEvent, _xmlReaderOptions)
  4469. {
  4470. init();
  4471. resetState();
  4472. }
  4473. protected:
  4474. virtual void reset() override
  4475. {
  4476. resetState();
  4477. PARENT::reset();
  4478. }
  4479. void readID(StringBuffer &id)
  4480. {
  4481. if (isValidXPathStartChr(nextChar))
  4482. {
  4483. for (;;)
  4484. {
  4485. id.append(nextChar);
  4486. readNext();
  4487. if (!isValidXPathChr(nextChar)) break;
  4488. }
  4489. }
  4490. }
  4491. void skipString()
  4492. {
  4493. if ('"' == nextChar)
  4494. {
  4495. do { readNext(); } while ('"' != nextChar);
  4496. }
  4497. else if ('\'' == nextChar)
  4498. {
  4499. do { readNext(); } while ('\'' != nextChar);
  4500. }
  4501. else expecting("\" or '");
  4502. }
  4503. bool lookupRefValue(const char *name, StringBuffer &value)
  4504. {
  4505. StringAttr *val = entityTable.getValue(name);
  4506. if (!val) return false;
  4507. value.append(*val);
  4508. return true;
  4509. }
  4510. void storeEntity(const char *name, const char *value)
  4511. {
  4512. entityTable.setValue(name, value);
  4513. }
  4514. void parseEntity()
  4515. {
  4516. try { match("NTITY"); }
  4517. catch (const char *) { error("Bad syntax"); }
  4518. readNext();
  4519. skipWS();
  4520. StringBuffer entityName;
  4521. if ('%' != nextChar)
  4522. {
  4523. readID(entityName);
  4524. skipWS();
  4525. if ('"' == nextChar)
  4526. {
  4527. StringBuffer refValue;
  4528. for (;;)
  4529. {
  4530. readNext();
  4531. if (!nextChar || '"' == nextChar)
  4532. break;
  4533. if ('&' == nextChar)
  4534. {
  4535. readNext();
  4536. StringBuffer ref;
  4537. if ('#' == nextChar)
  4538. {
  4539. ref.append("&#");
  4540. for (;;)
  4541. {
  4542. readNext();
  4543. if (!nextChar)
  4544. expecting(";");
  4545. if (';' == nextChar) break;
  4546. ref.append(nextChar);
  4547. }
  4548. ref.append(";");
  4549. decodeXML(ref, refValue);
  4550. }
  4551. else
  4552. {
  4553. readID(ref);
  4554. if (';' != nextChar)
  4555. expecting(";");
  4556. if (!lookupRefValue(ref, refValue))
  4557. {
  4558. StringBuffer _ref("&");
  4559. _ref.append(ref).append(';');
  4560. decodeXML(ref, refValue); // try inbuilts
  4561. }
  4562. }
  4563. }
  4564. else
  4565. refValue.append(nextChar);
  4566. }
  4567. storeEntity(entityName, refValue);
  4568. }
  4569. }
  4570. do { readNext(); }
  4571. while (nextChar && nextChar != '>');
  4572. }
  4573. void parseIntSubset()
  4574. {
  4575. for (;;)
  4576. {
  4577. readNext();
  4578. skipWS();
  4579. if (']'== nextChar) break;
  4580. if ('<' == nextChar)
  4581. {
  4582. readNext();
  4583. switch (nextChar)
  4584. {
  4585. case '!':
  4586. {
  4587. readNext();
  4588. switch (nextChar)
  4589. {
  4590. case '-':
  4591. parseComment();
  4592. break;
  4593. case 'E':
  4594. parseEntity();
  4595. break;
  4596. default: // ignore anything else
  4597. do { readNext(); }
  4598. while (nextChar && nextChar != '>');
  4599. break;
  4600. }
  4601. break;
  4602. }
  4603. case '?':
  4604. {
  4605. StringBuffer pi;
  4606. parsePI(pi);
  4607. break;
  4608. }
  4609. }
  4610. }
  4611. }
  4612. }
  4613. void parseOther()
  4614. {
  4615. switch (nextChar)
  4616. {
  4617. case '-':
  4618. parseComment2();
  4619. break;
  4620. case 'D':
  4621. {
  4622. try { match("OCTYPE"); }
  4623. catch (const char *) { error("Bad syntax"); }
  4624. readNext();
  4625. skipWS();
  4626. StringBuffer doctypeid;
  4627. readID(doctypeid);
  4628. for (;;)
  4629. {
  4630. skipWS();
  4631. if ('>' == nextChar) break;
  4632. if ('[' == nextChar)
  4633. {
  4634. parseIntSubset();
  4635. if (']' != nextChar)
  4636. expecting("]");
  4637. }
  4638. else if ('S' == nextChar)
  4639. {
  4640. match("YSTEM");
  4641. readNext();
  4642. skipWS();
  4643. skipString();
  4644. }
  4645. else if ('P' == nextChar)
  4646. {
  4647. match("UBLIC");
  4648. readNext();
  4649. skipWS();
  4650. skipString();
  4651. readNext();
  4652. skipWS();
  4653. skipString();
  4654. }
  4655. readNext();
  4656. }
  4657. break;
  4658. }
  4659. default:
  4660. error("Invalid information tag");
  4661. }
  4662. }
  4663. void parsePIOrDecl()
  4664. {
  4665. StringBuffer target;
  4666. parsePI(target);
  4667. if (0 == strcmp("xml", target.str()))
  4668. {
  4669. if (hadXMLDecl)
  4670. error("Only one XML declartion permitted");
  4671. hadXMLDecl = true;
  4672. }
  4673. }
  4674. void parseCData(StringBuffer &text)
  4675. {
  4676. try { match("CDATA["); }
  4677. catch (const char *) { error("Bad CDATA syntax"); }
  4678. for (;;)
  4679. {
  4680. readNext();
  4681. while (']' == nextChar)
  4682. {
  4683. readNext();
  4684. while (']' == nextChar)
  4685. {
  4686. readNext();
  4687. if ('>' == nextChar)
  4688. return;
  4689. else
  4690. text.append(']');
  4691. }
  4692. text.append(']');
  4693. }
  4694. text.append(nextChar);
  4695. }
  4696. }
  4697. void parsePI(StringBuffer &target)
  4698. {
  4699. readNext();
  4700. if (!isValidXPathStartChr(nextChar))
  4701. error("Invalid PI target");
  4702. for (;;)
  4703. {
  4704. target.append(nextChar);
  4705. readNext();
  4706. if (!isValidXPathChr(nextChar))
  4707. break;
  4708. }
  4709. skipWS();
  4710. unsigned closeTag=0;
  4711. for (;;)
  4712. {
  4713. if (!nextChar)
  4714. error("Missing closing PI tag ?>");
  4715. if (1 == closeTag)
  4716. {
  4717. if ('>' == nextChar)
  4718. break;
  4719. closeTag = 0;
  4720. }
  4721. else if ('?' == nextChar)
  4722. closeTag = 1;
  4723. readNext();
  4724. }
  4725. }
  4726. void parseDirective(StringBuffer &res)
  4727. {
  4728. readNext();
  4729. switch (nextChar) {
  4730. case '-':
  4731. parseComment2();
  4732. break;
  4733. case '[':
  4734. parseCData(res);
  4735. break;
  4736. default:
  4737. error("Unrecognised syntax");
  4738. }
  4739. }
  4740. void parseComment()
  4741. {
  4742. readNext();
  4743. if (nextChar != '-') error("Bad comment syntax");
  4744. parseComment2();
  4745. }
  4746. void parseComment2()
  4747. {
  4748. readNext();
  4749. if (nextChar != '-') error("Bad comment syntax");
  4750. readNext();
  4751. unsigned seen = 0;
  4752. while (nextChar)
  4753. {
  4754. if (seen==2)
  4755. {
  4756. if (nextChar=='>')
  4757. return;
  4758. else if (nextChar != '-') // should be syntax error really.
  4759. seen = 0;
  4760. }
  4761. else if (nextChar=='-')
  4762. seen++;
  4763. else
  4764. seen = 0;
  4765. readNext();
  4766. }
  4767. error("Bad comment syntax");
  4768. }
  4769. const char *_decodeXML(unsigned read, const char *startMark, StringBuffer &ret)
  4770. {
  4771. const char *errMark = NULL;
  4772. try { return decodeXML(startMark, ret, &errMark, this); }
  4773. catch (IException *e)
  4774. {
  4775. if (errMark)
  4776. rewind((unsigned)(errMark-startMark));
  4777. StringBuffer errMsg;
  4778. e->errorMessage(errMsg);
  4779. e->Release();
  4780. error(errMsg.str());
  4781. }
  4782. return NULL; // will never get here.
  4783. }
  4784. // IEntityHelper impl.
  4785. virtual bool find(const char *entity, StringBuffer &value) override
  4786. {
  4787. return lookupRefValue(entity, value);
  4788. }
  4789. };
  4790. template <class X>
  4791. class CXMLReader : public CXMLReaderBase<X>, implements IPTreeReader
  4792. {
  4793. bool rootTerminated;
  4794. StringBuffer attrName, attrval;
  4795. StringBuffer tmpStr;
  4796. void init()
  4797. {
  4798. attrName.append('@');
  4799. }
  4800. void resetState()
  4801. {
  4802. rootTerminated = false;
  4803. }
  4804. public:
  4805. typedef CXMLReaderBase<X> PARENT;
  4806. using PARENT::nextChar;
  4807. using PARENT::readNext;
  4808. using PARENT::expecting;
  4809. using PARENT::match;
  4810. using PARENT::error;
  4811. using PARENT::skipWS;
  4812. using PARENT::checkBOM;
  4813. using PARENT::checkReadNext;
  4814. using PARENT::checkSkipWS;
  4815. using PARENT::eos;
  4816. using PARENT::curOffset;
  4817. using PARENT::noRoot;
  4818. using PARENT::ignoreWhiteSpace;
  4819. using PARENT::iEvent;
  4820. using PARENT::parseDirective;
  4821. using PARENT::parseOther;
  4822. using PARENT::parsePI;
  4823. using PARENT::parsePIOrDecl;
  4824. using PARENT::parseComment;
  4825. using PARENT::_decodeXML;
  4826. using PARENT::ignoreNameSpaces;
  4827. using PARENT::hadXMLDecl;
  4828. IMPLEMENT_IINTERFACE;
  4829. CXMLReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize=0)
  4830. : PARENT(stream, iEvent, xmlReaderOptions, bufSize)
  4831. {
  4832. init();
  4833. resetState();
  4834. }
  4835. CXMLReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
  4836. : PARENT(buf, bufLength, iEvent, xmlReaderOptions)
  4837. {
  4838. init();
  4839. resetState();
  4840. }
  4841. CXMLReader(const void *buf, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
  4842. : PARENT(buf, iEvent, xmlReaderOptions)
  4843. {
  4844. init();
  4845. resetState();
  4846. }
  4847. virtual void reset() override
  4848. {
  4849. resetState();
  4850. PARENT::reset();
  4851. }
  4852. // IPTreeReader
  4853. virtual void load() override { loadXML(); }
  4854. virtual offset_t queryOffset() override { return curOffset; }
  4855. void loadXML()
  4856. {
  4857. bool head=true;
  4858. restart:
  4859. if (!checkReadNext()) return;
  4860. if (head)
  4861. {
  4862. head = false;
  4863. if (checkBOM())
  4864. if (!checkReadNext()) return;
  4865. }
  4866. if (!checkSkipWS()) return;
  4867. if ('<' != nextChar)
  4868. expecting("<");
  4869. readNext();
  4870. if ('!' == nextChar)
  4871. {
  4872. readNext();
  4873. parseOther();
  4874. goto restart;
  4875. }
  4876. else if ('?' == nextChar)
  4877. {
  4878. parsePIOrDecl();
  4879. goto restart;
  4880. }
  4881. if (!noRoot && rootTerminated)
  4882. {
  4883. if (ignoreWhiteSpace)
  4884. if (!checkSkipWS()) return;
  4885. error("Trailing xml after close of root tag");
  4886. }
  4887. _loadXML();
  4888. if (noRoot)
  4889. {
  4890. head = true;
  4891. hadXMLDecl = false;
  4892. }
  4893. else
  4894. rootTerminated = true;
  4895. goto restart;
  4896. }
  4897. void _loadXML()
  4898. {
  4899. restart:
  4900. offset_t startOffset = curOffset-2;
  4901. if ('!' == nextChar) // not sure this branch can ever be hit.
  4902. {
  4903. parseComment();
  4904. readNext();
  4905. if ('<' != nextChar)
  4906. expecting("<");
  4907. goto restart;
  4908. }
  4909. StringBuffer tagName;
  4910. if (ignoreWhiteSpace)
  4911. skipWS();
  4912. while (!isspace(nextChar) && nextChar != '>' && nextChar != '/')
  4913. {
  4914. tagName.append(nextChar);
  4915. readNext();
  4916. if ('<' == nextChar)
  4917. error("Unmatched close tag encountered");
  4918. }
  4919. StringBuffer completeTagname(tagName);
  4920. if (ignoreNameSpaces)
  4921. {
  4922. const char *colon;
  4923. if ((colon = strchr(tagName.str(), ':')) != NULL)
  4924. tagName.remove(0, (size32_t)(colon - tagName.str() + 1));
  4925. }
  4926. iEvent->beginNode(tagName.str(), false, startOffset);
  4927. skipWS();
  4928. bool endTag = false;
  4929. bool base64 = false;
  4930. while(nextChar != '>')
  4931. {
  4932. skipWS();
  4933. if (nextChar=='/')
  4934. {
  4935. readNext();
  4936. if (nextChar != '>')
  4937. expecting(">");
  4938. endTag = true;
  4939. break;
  4940. }
  4941. attrName.setLength(1);
  4942. attrval.clear();
  4943. while (nextChar && !isspace(nextChar) && nextChar != '=' && nextChar != '>' && nextChar != '/')
  4944. {
  4945. attrName.append(nextChar);
  4946. readNext();
  4947. }
  4948. skipWS();
  4949. if (nextChar == '=') readNext(); else expecting("=");
  4950. skipWS();
  4951. if (nextChar == '"')
  4952. {
  4953. readNext();
  4954. while (nextChar != '"')
  4955. {
  4956. if (!nextChar)
  4957. eos();
  4958. attrval.append(nextChar);
  4959. readNext();
  4960. }
  4961. }
  4962. else if (nextChar == '\'')
  4963. {
  4964. readNext();
  4965. while (nextChar != '\'')
  4966. {
  4967. attrval.append(nextChar);
  4968. readNext();
  4969. }
  4970. }
  4971. else
  4972. error();
  4973. _decodeXML(0, attrval.str(), tmpStr.clear());
  4974. if (0 == strcmp(attrName.str(), "@xsi:type") &&
  4975. (0 == stricmp(tmpStr.str(),"SOAP-ENC:base64")))
  4976. base64 = true;
  4977. else
  4978. iEvent->newAttribute(attrName.str(), tmpStr.str());
  4979. readNext();
  4980. skipWS();
  4981. }
  4982. iEvent->beginNodeContent(tagName.str());
  4983. StringBuffer tagText;
  4984. bool binary = base64;
  4985. if (!endTag)
  4986. {
  4987. if (nextChar == '>')
  4988. {
  4989. for (;;)
  4990. {
  4991. for (;;)
  4992. {
  4993. readNext();
  4994. if (ignoreWhiteSpace)
  4995. skipWS();
  4996. if ('\0' == nextChar)
  4997. eos();
  4998. StringBuffer mark;
  4999. while (nextChar && nextChar !='<') { mark.append(nextChar); readNext(); }
  5000. size32_t l = mark.length();
  5001. size32_t r = l+1;
  5002. if (l)
  5003. {
  5004. if (ignoreWhiteSpace)
  5005. {
  5006. while (l-- && isspace(mark.charAt(l)));
  5007. mark.setLength(l+1);
  5008. }
  5009. tagText.ensureCapacity(mark.length());
  5010. _decodeXML(r, mark.str(), tagText);
  5011. }
  5012. readNext();
  5013. if ('!' == nextChar)
  5014. parseDirective(tagText);
  5015. else if ('?' == nextChar)
  5016. {
  5017. parsePI(tmpStr.clear());
  5018. #ifdef STRICT_PI
  5019. if (0 == stricmp(tmpStr.str(), "xml"))
  5020. error("Reserved PI target used");
  5021. #endif
  5022. }
  5023. else
  5024. break;
  5025. }
  5026. if (nextChar=='/')
  5027. {
  5028. if (base64)
  5029. {
  5030. JBASE64_Decode(tagText.str(), tmpStr.clear());
  5031. tagText.swapWith(tmpStr);
  5032. }
  5033. else
  5034. {
  5035. if (strlen(tagText.str()) != tagText.length())
  5036. binary = true;
  5037. }
  5038. break; // exit
  5039. }
  5040. else
  5041. _loadXML();
  5042. }
  5043. readNext();
  5044. unsigned i = 0;
  5045. while (!isspace(nextChar) && nextChar != '>')
  5046. {
  5047. if ((i >= completeTagname.length()) ||
  5048. (nextChar != completeTagname.charAt(i++)))
  5049. error("Mismatched opening and closing tags");
  5050. readNext();
  5051. }
  5052. if (i != completeTagname.length())
  5053. error("Mismatched opening and closing tags");
  5054. skipWS();
  5055. if (nextChar != '>')
  5056. expecting(">");
  5057. }
  5058. }
  5059. iEvent->endNode(tagName.str(), tagText.length(), tagText.str(), binary, curOffset);
  5060. }
  5061. };
  5062. template <class X>
  5063. class CPullXMLReader : public CXMLReaderBase<X>, implements IPullPTreeReader
  5064. {
  5065. typedef CXMLReaderBase<X> PARENT;
  5066. using PARENT::nextChar;
  5067. using PARENT::readNext;
  5068. using PARENT::expecting;
  5069. using PARENT::match;
  5070. using PARENT::error;
  5071. using PARENT::skipWS;
  5072. using PARENT::checkBOM;
  5073. using PARENT::checkReadNext;
  5074. using PARENT::checkSkipWS;
  5075. using PARENT::eos;
  5076. using PARENT::curOffset;
  5077. using PARENT::noRoot;
  5078. using PARENT::ignoreWhiteSpace;
  5079. using PARENT::iEvent;
  5080. using PARENT::parseDirective;
  5081. using PARENT::parseOther;
  5082. using PARENT::parsePI;
  5083. using PARENT::parsePIOrDecl;
  5084. using PARENT::parseComment;
  5085. using PARENT::_decodeXML;
  5086. using PARENT::ignoreNameSpaces;
  5087. using PARENT::hadXMLDecl;
  5088. class CStateInfo : public CInterface
  5089. {
  5090. public:
  5091. CStateInfo()
  5092. {
  5093. tag.ensureCapacity(15);
  5094. binary = base64 = false;
  5095. }
  5096. inline void reset()
  5097. {
  5098. binary = base64 = false;
  5099. tag.clear();
  5100. tagText.clear();
  5101. }
  5102. const char *wnsTag;
  5103. StringBuffer tag;
  5104. StringBuffer tagText;
  5105. bool binary, base64;
  5106. };
  5107. CICopyArrayOf<CStateInfo> stack, freeStateInfo;
  5108. CStateInfo *stateInfo;
  5109. enum ParseStates { headerStart, tagStart, tagAttributes, tagContent, tagContent2, tagClose, tagEnd, tagMarker } state;
  5110. bool endOfRoot;
  5111. StringBuffer attrName, attrval, mark, tmpStr;
  5112. void resetState()
  5113. {
  5114. stack.kill();
  5115. state = headerStart;
  5116. stateInfo = NULL;
  5117. endOfRoot = false;
  5118. attrName.append('@');
  5119. }
  5120. public:
  5121. IMPLEMENT_IINTERFACE;
  5122. CPullXMLReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize=0)
  5123. : CXMLReaderBase<X>(stream, iEvent, xmlReaderOptions, bufSize)
  5124. {
  5125. resetState();
  5126. }
  5127. CPullXMLReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
  5128. : CXMLReaderBase<X>(buf, bufLength, iEvent, xmlReaderOptions)
  5129. {
  5130. resetState();
  5131. }
  5132. CPullXMLReader(const void *buf, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
  5133. : CXMLReaderBase<X>(buf, iEvent, xmlReaderOptions)
  5134. {
  5135. resetState();
  5136. }
  5137. ~CPullXMLReader()
  5138. {
  5139. ForEachItemIn(i, stack)
  5140. delete &stack.item(i);
  5141. ForEachItemIn(i2, freeStateInfo)
  5142. delete &freeStateInfo.item(i2);
  5143. }
  5144. // IPullPTreeReader
  5145. virtual void load() override
  5146. {
  5147. while (next()) {}
  5148. }
  5149. virtual void reset() override
  5150. {
  5151. PARENT::reset();
  5152. resetState();
  5153. }
  5154. virtual offset_t queryOffset() override { return curOffset; }
  5155. virtual bool next() override
  5156. {
  5157. switch (state)
  5158. {
  5159. case headerStart:
  5160. {
  5161. if (!checkReadNext()) return false;
  5162. if (checkBOM())
  5163. if (!checkReadNext()) return false;
  5164. for (;;)
  5165. {
  5166. if (!checkSkipWS()) return false;
  5167. if ('<' != nextChar)
  5168. expecting("<");
  5169. readNext();
  5170. if ('!' == nextChar)
  5171. {
  5172. readNext();
  5173. parseOther();
  5174. }
  5175. else if ('?' == nextChar)
  5176. parsePIOrDecl();
  5177. else
  5178. break;
  5179. if (!checkReadNext()) return false;
  5180. }
  5181. state = tagStart;
  5182. break;
  5183. }
  5184. case tagStart:
  5185. {
  5186. offset_t startOffset;
  5187. for (;;)
  5188. {
  5189. if ('!' != nextChar)
  5190. break;
  5191. parseComment();
  5192. readNext();
  5193. if ('<' != nextChar)
  5194. expecting("<");
  5195. }
  5196. startOffset = curOffset-2;
  5197. if (freeStateInfo.ordinality())
  5198. {
  5199. stateInfo = &freeStateInfo.popGet();
  5200. stateInfo->reset();
  5201. }
  5202. else
  5203. stateInfo = new CStateInfo;
  5204. stack.append(*stateInfo);
  5205. if ('/' == nextChar)
  5206. error("Unmatched close tag encountered");
  5207. while (!isspace(nextChar) && nextChar != '>')
  5208. {
  5209. stateInfo->tag.append(nextChar);
  5210. readNext();
  5211. if ('/' == nextChar) break;
  5212. if ('<' == nextChar)
  5213. error("Unmatched close tag encountered");
  5214. }
  5215. stateInfo->wnsTag = stateInfo->tag.str();
  5216. if (ignoreNameSpaces)
  5217. {
  5218. const char *colon;
  5219. if ((colon = strchr(stateInfo->wnsTag, ':')) != NULL)
  5220. stateInfo->wnsTag = colon+1;
  5221. }
  5222. endOfRoot = false;
  5223. try
  5224. {
  5225. iEvent->beginNode(stateInfo->wnsTag, false, startOffset);
  5226. }
  5227. catch (IPTreeException *pe)
  5228. {
  5229. if (PTreeExcpt_InvalidTagName == pe->errorCode())
  5230. {
  5231. pe->Release();
  5232. StringBuffer msg("Expecting valid start tag, but got \"");
  5233. error(msg.append(stateInfo->wnsTag).append("\"").str());
  5234. }
  5235. throw;
  5236. }
  5237. state = tagAttributes;
  5238. break;
  5239. }
  5240. case tagAttributes:
  5241. {
  5242. skipWS();
  5243. if (nextChar == '>')
  5244. state = tagContent;
  5245. else
  5246. {
  5247. skipWS();
  5248. if (nextChar=='/')
  5249. {
  5250. readNext();
  5251. if (nextChar != '>')
  5252. expecting(">");
  5253. // no actual content
  5254. iEvent->beginNodeContent(stateInfo->wnsTag);
  5255. state = tagEnd;
  5256. break;
  5257. }
  5258. attrName.setLength(1);
  5259. attrval.clear();
  5260. while (nextChar && !isspace(nextChar) && nextChar != '=' && nextChar != '>' && nextChar != '/')
  5261. {
  5262. attrName.append(nextChar);
  5263. readNext();
  5264. }
  5265. skipWS();
  5266. if (nextChar == '=') readNext(); else expecting("=");
  5267. skipWS();
  5268. if (nextChar == '"')
  5269. {
  5270. readNext();
  5271. while (nextChar != '"')
  5272. {
  5273. if (!nextChar)
  5274. eos();
  5275. attrval.append(nextChar);
  5276. readNext();
  5277. }
  5278. }
  5279. else if (nextChar == '\'')
  5280. {
  5281. readNext();
  5282. while (nextChar != '\'')
  5283. {
  5284. attrval.append(nextChar);
  5285. readNext();
  5286. }
  5287. }
  5288. else
  5289. error();
  5290. _decodeXML(0, attrval.str(), tmpStr.clear());
  5291. if (0 == strcmp(attrName.str(), "@xsi:type") &&
  5292. (0 == stricmp(tmpStr.str(),"SOAP-ENC:base64")))
  5293. stateInfo->base64 = true;
  5294. else
  5295. iEvent->newAttribute(attrName.str(), tmpStr.str());
  5296. readNext();
  5297. skipWS();
  5298. }
  5299. break;
  5300. }
  5301. case tagContent:
  5302. {
  5303. iEvent->beginNodeContent(stateInfo->wnsTag);
  5304. if ('>' != nextChar)
  5305. state = tagEnd;
  5306. else
  5307. state = tagContent2;
  5308. break;
  5309. }
  5310. case tagContent2:
  5311. {
  5312. try
  5313. {
  5314. for (;;)
  5315. {
  5316. if (endOfRoot)
  5317. {
  5318. if (!checkReadNext()) return false;
  5319. if (!checkSkipWS()) return false;
  5320. }
  5321. else
  5322. {
  5323. readNext();
  5324. if (ignoreWhiteSpace)
  5325. skipWS();
  5326. }
  5327. if ('\0' == nextChar)
  5328. eos();
  5329. mark.clear();
  5330. state = tagMarker;
  5331. while (nextChar && nextChar !='<') { mark.append(nextChar); readNext(); }
  5332. if (!nextChar)
  5333. break;
  5334. size32_t l = mark.length();
  5335. size32_t r = l+1;
  5336. if (l && stateInfo)
  5337. {
  5338. if (ignoreWhiteSpace)
  5339. {
  5340. const char *tb = mark.str();
  5341. const char *t = tb+l-1;
  5342. if (isspace(*t))
  5343. {
  5344. while (t != tb && isspace(*(--t)));
  5345. mark.setLength((size32_t)(t-tb+1));
  5346. }
  5347. }
  5348. stateInfo->tagText.ensureCapacity(mark.length());
  5349. _decodeXML(r, mark.str(), stateInfo->tagText);
  5350. }
  5351. if (endOfRoot && mark.length())
  5352. {
  5353. const char *m = mark.str();
  5354. const char *e = m+mark.length();
  5355. do { if (!isspace(*m++)) error("Trailing content after close of root tag"); }
  5356. while (m!=e);
  5357. }
  5358. readNext();
  5359. if ('!' == nextChar)
  5360. {
  5361. parseDirective(stateInfo->tagText);
  5362. state = tagContent2;
  5363. }
  5364. else if ('?' == nextChar)
  5365. {
  5366. parsePI(tmpStr.clear());
  5367. #ifdef STRICT_PI
  5368. if (0 == stricmp(tmpStr.str(), "xml"))
  5369. error("Reserved PI target used");
  5370. #endif
  5371. state = tagContent2;
  5372. }
  5373. else
  5374. break;
  5375. }
  5376. }
  5377. catch (IPTreeReadException *e)
  5378. {
  5379. if (endOfRoot && PTreeRead_EOS == e->errorCode() && (state != tagContent2 && mark.length())) // only to provide more meaningful error
  5380. {
  5381. const char *m = mark.str();
  5382. const char *es = m+mark.length();
  5383. do
  5384. {
  5385. if (!isspace(*m++))
  5386. {
  5387. e->Release();
  5388. error("Trailing content after close of root tag");
  5389. }
  5390. }
  5391. while (m!=es);
  5392. }
  5393. throw;
  5394. }
  5395. if ('/' == nextChar)
  5396. {
  5397. if (endOfRoot && !noRoot)
  5398. error("Trailing tag close after close of root tag");
  5399. if (stateInfo->base64)
  5400. {
  5401. JBASE64_Decode(stateInfo->tagText.str(), tmpStr.clear());
  5402. stateInfo->tagText.swapWith(tmpStr);
  5403. stateInfo->binary = true;
  5404. // next state tagContent2 still
  5405. }
  5406. else
  5407. {
  5408. if (strlen(stateInfo->tagText.str()) != stateInfo->tagText.length())
  5409. stateInfo->binary = true;
  5410. }
  5411. state = tagClose;
  5412. break; // exit
  5413. }
  5414. else
  5415. {
  5416. if (endOfRoot && !noRoot)
  5417. error("Trailing tag open after close of root tag");
  5418. state = tagStart;
  5419. }
  5420. break;
  5421. }
  5422. case tagClose:
  5423. {
  5424. readNext();
  5425. const char *t = stateInfo->tag.str();
  5426. const char *te = t+stateInfo->tag.length();
  5427. for (;;)
  5428. {
  5429. if (nextChar == '>' || isspace(nextChar))
  5430. {
  5431. if (t != te)
  5432. error("Mismatched opening and closing tags");
  5433. break;
  5434. }
  5435. else if (nextChar != *t++)
  5436. error("Mismatched opening and closing tags");
  5437. readNext();
  5438. }
  5439. skipWS();
  5440. if (nextChar != '>')
  5441. expecting(">");
  5442. state = tagEnd;
  5443. break;
  5444. }
  5445. case tagEnd:
  5446. {
  5447. iEvent->endNode(stateInfo->wnsTag, stateInfo->tagText.length(), stateInfo->tagText.str(), stateInfo->binary, curOffset);
  5448. freeStateInfo.append(*stateInfo);
  5449. stack.pop();
  5450. endOfRoot = 0==stack.ordinality();
  5451. stateInfo = stack.ordinality()?&stack.tos():NULL;
  5452. if (endOfRoot && noRoot)
  5453. {
  5454. state = headerStart;
  5455. hadXMLDecl = false;
  5456. endOfRoot = false;
  5457. }
  5458. else
  5459. state = tagContent2;
  5460. break;
  5461. }
  5462. }
  5463. return true;
  5464. }
  5465. };
  5466. IPTreeReader *createXMLStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize)
  5467. {
  5468. class CXMLStreamReader : public CXMLReader<CInstStreamReader>
  5469. {
  5470. public:
  5471. CXMLStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize=0) : CXMLReader<CInstStreamReader>(stream, iEvent, xmlReaderOptions, bufSize) { }
  5472. };
  5473. return new CXMLStreamReader(stream, iEvent, xmlReaderOptions, bufSize);
  5474. }
  5475. IPTreeReader *createXMLStringReader(const char *xml, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
  5476. {
  5477. class CXMLStringReader : public CXMLReader<CInstStringReader>
  5478. {
  5479. public:
  5480. CXMLStringReader(const void *xml, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions) : CXMLReader<CInstStringReader>(xml, iEvent, xmlReaderOptions) { }
  5481. };
  5482. if (NULL == xml)
  5483. throw createPTreeReadException(PTreeRead_syntax, "Null string passed to createXMLStringReader", NULL, 0, 0);
  5484. return new CXMLStringReader(xml, iEvent, xmlReaderOptions);
  5485. }
  5486. IPTreeReader *createXMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
  5487. {
  5488. class CXMLBufferReader : public CXMLReader<CInstBufferReader>
  5489. {
  5490. public:
  5491. CXMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions) : CXMLReader<CInstBufferReader>(buf, bufLength, iEvent, xmlReaderOptions) { }
  5492. };
  5493. return new CXMLBufferReader(buf, bufLength, iEvent, xmlReaderOptions);
  5494. }
  5495. IPullPTreeReader *createPullXMLStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize)
  5496. {
  5497. class CXMLStreamReader : public CPullXMLReader<CInstStreamReader>
  5498. {
  5499. public:
  5500. CXMLStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize=0) : CPullXMLReader<CInstStreamReader>(stream, iEvent, xmlReaderOptions, bufSize) { }
  5501. };
  5502. return new CXMLStreamReader(stream, iEvent, xmlReaderOptions, bufSize);
  5503. }
  5504. IPullPTreeReader *createPullXMLStringReader(const char *xml, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
  5505. {
  5506. class CXMLStringReader : public CPullXMLReader<CInstStringReader>
  5507. {
  5508. public:
  5509. CXMLStringReader(const void *xml, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions) : CPullXMLReader<CInstStringReader>(xml, iEvent, xmlReaderOptions) { }
  5510. };
  5511. return new CXMLStringReader(xml, iEvent, xmlReaderOptions);
  5512. }
  5513. IPullPTreeReader *createPullXMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
  5514. {
  5515. class CXMLBufferReader : public CPullXMLReader<CInstBufferReader>
  5516. {
  5517. public:
  5518. CXMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions) : CPullXMLReader<CInstBufferReader>(buf, bufLength, iEvent, xmlReaderOptions) { }
  5519. };
  5520. return new CXMLBufferReader(buf, bufLength, iEvent, xmlReaderOptions);
  5521. }
  5522. IPTreeMaker *createPTreeMaker(byte flags, IPropertyTree *root, IPTreeNodeCreator *nodeCreator)
  5523. {
  5524. return new CPTreeMaker(flags, nodeCreator, root);
  5525. }
  5526. IPTreeMaker *createRootLessPTreeMaker(byte flags, IPropertyTree *root, IPTreeNodeCreator *nodeCreator)
  5527. {
  5528. return new CPTreeMaker(flags, nodeCreator, root, true);
  5529. }
  5530. ////////////////////////////
  5531. ///////////////////////////
  5532. static IPTreeMaker *createDefaultPTreeMaker(byte flags, PTreeReaderOptions readFlags)
  5533. {
  5534. bool noRoot = 0 != ((unsigned)readFlags & (unsigned)ptr_noRoot);
  5535. return new CPTreeMaker(flags, NULL, NULL, noRoot);
  5536. }
  5537. IPropertyTree *createPTree(ISimpleReadStream &stream, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  5538. {
  5539. Owned<IPTreeMaker> _iMaker;
  5540. if (!iMaker)
  5541. {
  5542. iMaker = createDefaultPTreeMaker(flags, readFlags);
  5543. _iMaker.setown(iMaker);
  5544. }
  5545. Owned<IPTreeReader> reader = createXMLStreamReader(stream, *iMaker, readFlags);
  5546. reader->load();
  5547. if (iMaker->queryRoot())
  5548. return LINK(iMaker->queryRoot());
  5549. else
  5550. return iMaker->create(NULL);
  5551. }
  5552. IPropertyTree *createPTree(IFileIO &ifileio, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  5553. {
  5554. OwnedIFileIOStream stream = createIOStream(&ifileio);
  5555. return createPTree(*stream, flags, readFlags, iMaker);
  5556. }
  5557. IPropertyTree *createPTree(IFile &ifile, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  5558. {
  5559. OwnedIFileIO ifileio = ifile.open(IFOread);
  5560. if (!ifileio)
  5561. throw MakeStringException(0, "Could not locate filename: %s", ifile.queryFilename());
  5562. return createPTree(*ifileio, flags, readFlags, iMaker);
  5563. }
  5564. IPropertyTree *createPTreeFromXMLFile(const char *filename, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  5565. {
  5566. OwnedIFile ifile = createIFile(filename);
  5567. return createPTree(*ifile, flags, readFlags, iMaker);
  5568. }
  5569. IPropertyTree *createPTreeFromXMLString(const char *xml, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  5570. {
  5571. Owned<IPTreeMaker> _iMaker;
  5572. if (!iMaker)
  5573. {
  5574. iMaker = createDefaultPTreeMaker(flags, readFlags);
  5575. _iMaker.setown(iMaker);
  5576. }
  5577. Owned<IPTreeReader> reader = createXMLStringReader(xml, *iMaker, readFlags);
  5578. reader->load();
  5579. return LINK(iMaker->queryRoot());
  5580. }
  5581. IPropertyTree *createPTreeFromXMLString(unsigned len, const char *xml, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  5582. {
  5583. Owned<IPTreeMaker> _iMaker;
  5584. if (!iMaker)
  5585. {
  5586. iMaker = createDefaultPTreeMaker(flags, readFlags);
  5587. _iMaker.setown(iMaker);
  5588. }
  5589. Owned<IPTreeReader> reader = createXMLBufferReader(xml, len, *iMaker, readFlags);
  5590. reader->load();
  5591. return LINK(iMaker->queryRoot());
  5592. }
  5593. //////////////////////////
  5594. /////////////////////////
  5595. inline bool isHiddenWhenSanitized(const char *val)
  5596. {
  5597. if (!val || !*val)
  5598. return false;
  5599. return !(streq(val, "0") || streq(val, "1") || strieq(val, "true") || strieq(val, "false") || strieq(val, "yes") || strieq(val, "no"));
  5600. }
  5601. inline bool isSanitizedAndHidden(const char *val, byte flags, bool attribute)
  5602. {
  5603. bool sanitize = (attribute) ? ((flags & YAML_SanitizeAttributeValues)!=0) : ((flags & YAML_Sanitize)!=0);
  5604. if (sanitize)
  5605. return isHiddenWhenSanitized(val);
  5606. return false;
  5607. }
  5608. static void _toXML(const IPropertyTree *tree, IIOStream &out, unsigned indent, unsigned flags)
  5609. {
  5610. const char *name = tree->queryName();
  5611. if (!name) name = "__unnamed__";
  5612. bool isBinary = tree->isBinary(NULL);
  5613. bool inlinebody = true;
  5614. if (flags & XML_Embed) writeCharsNToStream(out, ' ', indent);
  5615. writeCharToStream(out, '<');
  5616. writeStringToStream(out, name);
  5617. Owned<IAttributeIterator> it = tree->getAttributes(true);
  5618. if (it->first())
  5619. {
  5620. unsigned attributeindent = indent+2+(size32_t)strlen(name);
  5621. bool first = true;
  5622. do
  5623. {
  5624. const char *key = it->queryName();
  5625. if (!isBinary || stricmp(key, "@xsi:type")!=0)
  5626. {
  5627. if (first)
  5628. {
  5629. if (flags & XML_LineBreak) inlinebody = false;
  5630. first = false;
  5631. writeCharToStream(out, ' ');
  5632. }
  5633. else if ((flags & XML_LineBreakAttributes) && it->count() > 3)
  5634. {
  5635. writeStringToStream(out, "\n");
  5636. writeCharsNToStream(out, ' ', attributeindent);
  5637. }
  5638. else
  5639. writeCharToStream(out, ' ');
  5640. writeStringToStream(out, key+1);
  5641. if (flags & XML_SingleQuoteAttributeValues)
  5642. writeStringToStream(out, "='");
  5643. else
  5644. writeStringToStream(out, "=\"");
  5645. const char *val = it->queryValue();
  5646. if (val)
  5647. {
  5648. if (isSanitizedAndHidden(val, flags, true))
  5649. writeCharsNToStream(out, '*', strlen(val));
  5650. else
  5651. encodeXML(val, out, ENCODE_NEWLINES, (unsigned)-1, true);
  5652. }
  5653. if (flags & XML_SingleQuoteAttributeValues)
  5654. writeCharToStream(out, '\'');
  5655. else
  5656. writeCharToStream(out, '"');
  5657. }
  5658. }
  5659. while (it->next());
  5660. }
  5661. Owned<IPropertyTreeIterator> sub = tree->getElements("*", 0 != (flags & XML_SortTags) ? iptiter_sort : iptiter_null);
  5662. MemoryBuffer thislevelbin;
  5663. StringBuffer _thislevel;
  5664. const char *thislevel = NULL; // to avoid uninitialized warning
  5665. bool empty;
  5666. if (isBinary)
  5667. {
  5668. if (flags & XML_LineBreak) inlinebody = false;
  5669. writeStringToStream(out, " xsi:type=\"SOAP-ENC:base64\"");
  5670. empty = (!tree->getPropBin(NULL, thislevelbin))||(thislevelbin.length()==0);
  5671. }
  5672. else
  5673. {
  5674. if (tree->isCompressed(NULL))
  5675. {
  5676. empty = false; // can't be empty if compressed;
  5677. verifyex(tree->getProp(NULL, _thislevel));
  5678. thislevel = _thislevel.str();
  5679. }
  5680. else
  5681. empty = (NULL == (thislevel = tree->queryProp(NULL)));
  5682. }
  5683. if (sub->first())
  5684. {
  5685. if (flags & XML_LineBreak) inlinebody = false;
  5686. }
  5687. else if (empty && !(flags & XML_Sanitize))
  5688. {
  5689. if (flags & XML_LineBreak)
  5690. writeStringToStream(out, "/>\n");
  5691. else
  5692. writeStringToStream(out, "/>");
  5693. return;
  5694. }
  5695. writeCharToStream(out, '>');
  5696. if (!inlinebody)
  5697. writeStringToStream(out, "\n");
  5698. for(; sub->isValid(); sub->next())
  5699. _toXML(&sub->query(), out, indent+1, flags);
  5700. if (!empty)
  5701. {
  5702. if (!inlinebody)
  5703. writeCharsNToStream(out, ' ', indent+1);
  5704. if (flags & XML_Sanitize)
  5705. {
  5706. // NOTE - we don't output anything for binary.... is that ok?
  5707. if (thislevel)
  5708. {
  5709. if (isHiddenWhenSanitized(thislevel))
  5710. writeCharsNToStream(out, '*', strlen(thislevel));
  5711. else
  5712. writeStringToStream(out, thislevel);
  5713. }
  5714. }
  5715. else if (isBinary)
  5716. {
  5717. if (flags & XML_NoBinaryEncode64)
  5718. {
  5719. if (flags & XML_NoEncode)
  5720. {
  5721. out.write(thislevelbin.length(), thislevelbin.toByteArray());
  5722. }
  5723. else
  5724. {
  5725. const char * buff = static_cast<const char *>(thislevelbin.toByteArray());
  5726. const unsigned len = thislevelbin.length();
  5727. unsigned prefix = 0;
  5728. while ((prefix < len) && isspace(buff[prefix]))
  5729. prefix++;
  5730. encodeXML(buff, out, ENCODE_WHITESPACE, prefix, true);
  5731. if (prefix != len) { // check not all spaces
  5732. unsigned suffix = len;
  5733. while (isspace(buff[suffix-1]))
  5734. suffix--;
  5735. encodeXML(buff+prefix, out, 0, suffix-prefix, true);
  5736. encodeXML(buff+suffix, out, ENCODE_WHITESPACE, len-suffix, true);
  5737. }
  5738. }
  5739. }
  5740. else
  5741. JBASE64_Encode(thislevelbin.toByteArray(), thislevelbin.length(), out, true);
  5742. }
  5743. else
  5744. {
  5745. if (flags & XML_NoEncode)
  5746. {
  5747. writeStringToStream(out, thislevel);
  5748. }
  5749. else
  5750. {
  5751. const char *m = thislevel;
  5752. const char *p = m;
  5753. while (isspace(*p))
  5754. p++;
  5755. encodeXML(m, out, ENCODE_WHITESPACE, p-m, true);
  5756. if (*p) { // check not all spaces
  5757. const char *s = p+strlen(p);
  5758. while (isspace(*(s-1)))
  5759. s--;
  5760. assertex(s>p);
  5761. encodeXML(p, out, 0, s-p, true);
  5762. encodeXML(s, out, ENCODE_WHITESPACE, (unsigned)-1, true);
  5763. }
  5764. }
  5765. if (!inlinebody)
  5766. writeStringToStream(out, "\n");
  5767. }
  5768. }
  5769. if (!inlinebody)
  5770. writeCharsNToStream(out, ' ', indent);
  5771. writeStringToStream(out, "</");
  5772. writeStringToStream(out, name);
  5773. if (flags & XML_LineBreak)
  5774. writeStringToStream(out, ">\n");
  5775. else
  5776. writeCharToStream(out, '>');
  5777. }
  5778. class CStringBufferMarkupIOAdapter : public CInterfaceOf<IIOStream>
  5779. {
  5780. StringBuffer &out;
  5781. public:
  5782. CStringBufferMarkupIOAdapter(StringBuffer &_out) : out(_out) { }
  5783. virtual void flush() override { }
  5784. virtual size32_t read(size32_t len, void * data) override { UNIMPLEMENTED; return 0; }
  5785. virtual size32_t write(size32_t len, const void * data) override { out.append(len, (const char *)data); return len; }
  5786. };
  5787. jlib_decl StringBuffer &toXML(const IPropertyTree *tree, StringBuffer &ret, unsigned indent, unsigned flags)
  5788. {
  5789. CStringBufferMarkupIOAdapter adapter(ret);
  5790. _toXML(tree->queryBranch(NULL), adapter, indent, flags);
  5791. return ret;
  5792. }
  5793. void toXML(const IPropertyTree *tree, IIOStream &out, unsigned indent, unsigned flags)
  5794. {
  5795. _toXML(tree, out, indent, flags);
  5796. }
  5797. void printXML(const IPropertyTree *tree, unsigned indent, unsigned flags)
  5798. {
  5799. StringBuffer xml;
  5800. toXML(tree, xml, indent, flags);
  5801. printf("%s", xml.str());
  5802. }
  5803. void dbglogXML(const IPropertyTree *tree, unsigned indent, unsigned flags)
  5804. {
  5805. StringBuffer xml;
  5806. toXML(tree, xml, indent, flags);
  5807. DBGLOG("%s", xml.str());
  5808. }
  5809. void saveXML(const char *filename, const IPropertyTree *tree, unsigned indent, unsigned flags)
  5810. {
  5811. OwnedIFile ifile = createIFile(filename);
  5812. saveXML(*ifile, tree, indent, flags);
  5813. }
  5814. void saveXML(IFile &ifile, const IPropertyTree *tree, unsigned indent, unsigned flags)
  5815. {
  5816. OwnedIFileIO ifileio = ifile.open(IFOcreate);
  5817. if (!ifileio)
  5818. throw MakeStringException(0, "saveXML: could not find %s to open", ifile.queryFilename());
  5819. saveXML(*ifileio, tree, indent, flags);
  5820. }
  5821. void saveXML(IFileIO &ifileio, const IPropertyTree *tree, unsigned indent, unsigned flags)
  5822. {
  5823. Owned<IIOStream> stream = createIOStream(&ifileio);
  5824. stream.setown(createBufferedIOStream(stream));
  5825. saveXML(*stream, tree, indent, flags);
  5826. }
  5827. void saveXML(IIOStream &stream, const IPropertyTree *tree, unsigned indent, unsigned flags)
  5828. {
  5829. toXML(tree, stream, indent, flags);
  5830. }
  5831. /////////////////////////
  5832. void checkWriteJSONDelimiter(IIOStream &out, bool &delimit)
  5833. {
  5834. if (delimit)
  5835. writeCharToStream(out, ',');
  5836. delimit = false;
  5837. }
  5838. static void writeJSONNameToStream(IIOStream &out, const char *name, unsigned indent, bool &delimit)
  5839. {
  5840. if (!name || !*name)
  5841. return;
  5842. checkWriteJSONDelimiter(out, delimit);
  5843. if (indent)
  5844. {
  5845. writeCharToStream(out, '\n');
  5846. writeCharsNToStream(out, ' ', indent);
  5847. }
  5848. else
  5849. writeCharToStream(out, ' ');
  5850. writeCharToStream(out, '"');
  5851. writeStringToStream(out, name);
  5852. writeStringToStream(out, "\": ");
  5853. delimit = false;
  5854. }
  5855. static void writeJSONValueToStream(IIOStream &out, const char *val, bool &delimit, bool hidden=false)
  5856. {
  5857. checkWriteJSONDelimiter(out, delimit);
  5858. delimit = true;
  5859. if (!val)
  5860. {
  5861. writeStringToStream(out, "null");
  5862. return;
  5863. }
  5864. writeCharToStream(out, '"');
  5865. if (hidden)
  5866. writeCharsNToStream(out, '*', strlen(val));
  5867. else
  5868. {
  5869. StringBuffer s;
  5870. writeStringToStream(out, encodeJSON(s, val));
  5871. }
  5872. writeCharToStream(out, '"');
  5873. }
  5874. static void writeJSONBase64ValueToStream(IIOStream &out, const char *val, size32_t len, bool &delimit, bool hidden)
  5875. {
  5876. checkWriteJSONDelimiter(out, delimit);
  5877. delimit = true;
  5878. if (!val)
  5879. {
  5880. writeStringToStream(out, "null");
  5881. return;
  5882. }
  5883. writeCharToStream(out, '"');
  5884. if (hidden)
  5885. JBASE64_Encode("****", strlen("****"), out, false);
  5886. else
  5887. JBASE64_Encode(val, len, out, false);
  5888. writeCharToStream(out, '"');
  5889. }
  5890. bool isRootArrayObjectHidden(bool root, const char *name, byte flags)
  5891. {
  5892. return ((flags & JSON_HideRootArrayObject) && root && name && streq(name,"__array__"));
  5893. }
  5894. static void _toJSON(const IPropertyTree *tree, IIOStream &out, unsigned indent, byte flags, bool &delimit, bool root=false, bool isArrayItem=false)
  5895. {
  5896. Owned<IAttributeIterator> it = tree->getAttributes(true);
  5897. bool hasAttributes = it->first();
  5898. bool complex = (hasAttributes || tree->hasChildren() || tree->isBinary());
  5899. bool isBinary = tree->isBinary(NULL);
  5900. const char *name = tree->queryName();
  5901. if (!root && !isArrayItem)
  5902. {
  5903. if (!name || !*name)
  5904. name = "__unnamed__";
  5905. writeJSONNameToStream(out, name, (flags & JSON_Format) ? indent : 0, delimit);
  5906. }
  5907. checkWriteJSONDelimiter(out, delimit);
  5908. if (isArrayItem && (flags & JSON_Format))
  5909. {
  5910. writeCharToStream(out, '\n');
  5911. writeCharsNToStream(out, ' ', indent);
  5912. }
  5913. bool hiddenRootArrayObject = isRootArrayObjectHidden(root, name, flags);
  5914. if (!hiddenRootArrayObject)
  5915. {
  5916. if (root || complex)
  5917. {
  5918. writeCharToStream(out, '{');
  5919. delimit = false;
  5920. }
  5921. if (hasAttributes)
  5922. {
  5923. ForEach(*it)
  5924. {
  5925. const char *key = it->queryName();
  5926. if (!isBinary || stricmp(key, "@xsi:type")!=0)
  5927. {
  5928. const char *val = it->queryValue();
  5929. if (val)
  5930. {
  5931. writeJSONNameToStream(out, key, (flags & JSON_Format) ? indent+1 : 0, delimit);
  5932. if (flags & JSON_SanitizeAttributeValues)
  5933. writeJSONValueToStream(out, val, delimit, isHiddenWhenSanitized(val));
  5934. else
  5935. {
  5936. StringBuffer encoded;
  5937. encodeJSON(encoded, val);
  5938. writeJSONValueToStream(out, encoded.str(), delimit);
  5939. }
  5940. }
  5941. }
  5942. }
  5943. }
  5944. }
  5945. MemoryBuffer thislevelbin;
  5946. StringBuffer _thislevel;
  5947. const char *thislevel = NULL; // to avoid uninitialized warning
  5948. bool isNull = true;
  5949. if (!hiddenRootArrayObject)
  5950. {
  5951. if (isBinary)
  5952. {
  5953. isNull = (!tree->getPropBin(NULL, thislevelbin))||(thislevelbin.length()==0);
  5954. }
  5955. else
  5956. {
  5957. if (tree->isCompressed(NULL))
  5958. {
  5959. isNull = false; // can't be empty if compressed;
  5960. verifyex(tree->getProp(NULL, _thislevel));
  5961. thislevel = _thislevel.str();
  5962. }
  5963. else
  5964. isNull = (NULL == (thislevel = tree->queryProp(NULL)));
  5965. }
  5966. if (isNull && !root && !complex)
  5967. {
  5968. writeJSONValueToStream(out, NULL, delimit);
  5969. return;
  5970. }
  5971. }
  5972. Owned<IPropertyTreeIterator> sub = tree->getElements(hiddenRootArrayObject ? "__item__" : "*", 0 != (flags & JSON_SortTags) ? iptiter_sort : iptiter_null);
  5973. //note that detection of repeating elements relies on the fact that ptree elements
  5974. //of the same name will be grouped together
  5975. bool repeatingElement = false;
  5976. sub->first();
  5977. while(sub->isValid())
  5978. {
  5979. Linked<IPropertyTree> element = &sub->query();
  5980. const char *name = element->queryName();
  5981. sub->next();
  5982. if (!repeatingElement)
  5983. {
  5984. if (hiddenRootArrayObject)
  5985. {
  5986. writeCharToStream(out, '[');
  5987. repeatingElement = true;
  5988. delimit = false;
  5989. }
  5990. else if (sub->isValid() && streq(name, sub->query().queryName()))
  5991. {
  5992. if (flags & JSON_Format)
  5993. indent++;
  5994. writeJSONNameToStream(out, name, (flags & JSON_Format) ? indent : 0, delimit);
  5995. writeCharToStream(out, '[');
  5996. repeatingElement = true;
  5997. delimit = false;
  5998. }
  5999. }
  6000. _toJSON(element, out, indent+1, flags, delimit, false, repeatingElement);
  6001. if (repeatingElement && (!sub->isValid() || !streq(name, sub->query().queryName())))
  6002. {
  6003. if (flags & JSON_Format)
  6004. {
  6005. writeCharToStream(out, '\n');
  6006. writeCharsNToStream(out, ' ', indent);
  6007. indent--;
  6008. }
  6009. writeCharToStream(out, ']');
  6010. repeatingElement = false;
  6011. delimit = true;
  6012. }
  6013. }
  6014. if (!hiddenRootArrayObject && !isNull)
  6015. {
  6016. if (complex)
  6017. writeJSONNameToStream(out, isBinary ? "#valuebin" : "#value", (flags & JSON_Format) ? indent+1 : 0, delimit);
  6018. if (isBinary)
  6019. writeJSONBase64ValueToStream(out, thislevelbin.toByteArray(), thislevelbin.length(), delimit, flags & XML_Sanitize);
  6020. else
  6021. {
  6022. writeJSONValueToStream(out, thislevel, delimit, isSanitizedAndHidden(thislevel, flags, false));
  6023. }
  6024. }
  6025. if (!hiddenRootArrayObject)
  6026. {
  6027. if (root || complex)
  6028. {
  6029. if (flags & JSON_Format)
  6030. {
  6031. writeCharToStream(out, '\n');
  6032. writeCharsNToStream(out, ' ', indent);
  6033. }
  6034. writeCharToStream(out, '}');
  6035. delimit = true;
  6036. }
  6037. }
  6038. }
  6039. jlib_decl StringBuffer &toJSON(const IPropertyTree *tree, StringBuffer &ret, unsigned indent, byte flags)
  6040. {
  6041. CStringBufferMarkupIOAdapter adapter(ret);
  6042. bool delimit = false;
  6043. _toJSON(tree->queryBranch(NULL), adapter, indent, flags, delimit, true);
  6044. return ret;
  6045. }
  6046. void toJSON(const IPropertyTree *tree, IIOStream &out, unsigned indent, byte flags)
  6047. {
  6048. bool delimit = false;
  6049. _toJSON(tree, out, indent, flags, delimit, true);
  6050. }
  6051. void printJSON(const IPropertyTree *tree, unsigned indent, byte flags)
  6052. {
  6053. StringBuffer json;
  6054. toJSON(tree, json, indent, flags);
  6055. printf("%s", json.str());
  6056. }
  6057. void dbglogJSON(const IPropertyTree *tree, unsigned indent, unsigned flags)
  6058. {
  6059. StringBuffer json;
  6060. toJSON(tree, json, indent, flags);
  6061. DBGLOG("%s", json.str());
  6062. }
  6063. static inline void skipWS(const char *&xpath)
  6064. {
  6065. while (isspace(*xpath)) xpath++;
  6066. }
  6067. static void _validateXPathSyntax(const char *xpath);
  6068. static void validateQualifier(const char *&xxpath)
  6069. {
  6070. const char *xpath = xxpath;
  6071. const char *start = xpath;
  6072. skipWS(xpath);
  6073. const char *lhsStart = xpath;
  6074. for (;;)
  6075. {
  6076. switch (*xpath) {
  6077. case ']':
  6078. case '!':
  6079. case '=':
  6080. case '\0':
  6081. break;
  6082. default:
  6083. if (!isspace(*xpath))
  6084. {
  6085. xpath++;
  6086. continue;
  6087. }
  6088. }
  6089. break;
  6090. }
  6091. StringAttr lhs(lhsStart, xpath-lhsStart);
  6092. _validateXPathSyntax(lhs);
  6093. skipWS(xpath);
  6094. exprType tType = t_none;
  6095. if ('=' == *xpath)
  6096. {
  6097. ++xpath;
  6098. tType = t_equality;
  6099. }
  6100. else if ('!' == *xpath)
  6101. {
  6102. ++xpath;
  6103. if (*xpath && '=' == *xpath)
  6104. {
  6105. tType = t_inequality;
  6106. ++xpath;
  6107. }
  6108. else
  6109. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, 0, "Invalid qualifier expression");
  6110. }
  6111. if (t_none != tType)
  6112. {
  6113. skipWS(xpath);
  6114. if ('~' == *xpath)
  6115. {
  6116. ++xpath; // Signifies wild (now always true but still accepted...)
  6117. }
  6118. skipWS(xpath);
  6119. char qu = *xpath;
  6120. if (qu != '\'' && qu != '\"')
  6121. throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Syntax error - no opening \" or \'");
  6122. ++xpath;
  6123. while (*xpath && *xpath != qu)
  6124. xpath++;
  6125. if (!*xpath)
  6126. throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Syntax error - no closing \" or \'");
  6127. xpath++;
  6128. }
  6129. skipWS(xpath);
  6130. if (']' != *xpath)
  6131. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, 0, "No closing brace to qualifier");
  6132. xxpath = xpath;
  6133. }
  6134. static void _validateXPathSyntax(const char *xpath)
  6135. {
  6136. if (NULL == xpath || '\0' == *xpath)
  6137. return;
  6138. else
  6139. {
  6140. const char *_xpath = xpath;
  6141. restart:
  6142. if (NULL == xpath || '\0' == *xpath)
  6143. return;
  6144. switch (*xpath)
  6145. {
  6146. case '.':
  6147. ++xpath;
  6148. goto restart;
  6149. case '/':
  6150. ++xpath;
  6151. if ('/' == *xpath)
  6152. {
  6153. _validateXPathSyntax(xpath+1);
  6154. return;
  6155. }
  6156. goto restart;
  6157. case '[':
  6158. {
  6159. ++xpath;
  6160. if (isdigit(*xpath))
  6161. {
  6162. StringAttr index;
  6163. xpath = readIndex(xpath, index);
  6164. unsigned i = atoi(index.get());
  6165. if (i)
  6166. {
  6167. }
  6168. else
  6169. {
  6170. // should be syntax error
  6171. }
  6172. if (']' != *xpath)
  6173. throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
  6174. }
  6175. else
  6176. validateQualifier(xpath);
  6177. ++xpath;
  6178. break;
  6179. }
  6180. default:
  6181. {
  6182. bool wild;
  6183. const char *start = xpath;
  6184. readWildId(xpath, wild); // validates also
  6185. size32_t s = xpath-start;
  6186. if (s)
  6187. {
  6188. StringAttr id(start, s);
  6189. if ('[' == *xpath) // check for local index not iterative qualifier.
  6190. {
  6191. const char *xxpath = xpath+1;
  6192. if (isdigit(*xxpath))
  6193. {
  6194. StringAttr idxstr;
  6195. xxpath = readIndex(xxpath, idxstr);
  6196. if (']' != *xxpath)
  6197. throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
  6198. ++xxpath;
  6199. unsigned index = atoi(idxstr.get());
  6200. if (index)
  6201. {
  6202. }
  6203. xpath = xxpath;
  6204. }
  6205. }
  6206. }
  6207. else if ('@' == *xpath)
  6208. {
  6209. ++xpath;
  6210. const char *start = xpath;
  6211. readID(xpath, false);
  6212. size32_t s = xpath-start;
  6213. if (!s)
  6214. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Missing attribute?");
  6215. StringAttr id(start, s);
  6216. if (!validateXMLTag(id))
  6217. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Invalid xml tag: %s", id.get());
  6218. while (isspace(*xpath)) xpath++;
  6219. if ('\0' != *xpath)
  6220. throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Cannot have embedded attribute within path (must be tail component)");
  6221. }
  6222. else
  6223. {
  6224. if ('[' != *xpath)
  6225. throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Qualifier expected e.g. [..]");
  6226. validateQualifier(xpath);
  6227. }
  6228. break;
  6229. }
  6230. }
  6231. }
  6232. if (*xpath == '\0' || (*xpath == '/' && '\0' == *(xpath+1)))
  6233. return;
  6234. else
  6235. _validateXPathSyntax(xpath);
  6236. }
  6237. bool validateXPathSyntax(const char *xpath, StringBuffer *error)
  6238. {
  6239. try
  6240. {
  6241. if (xpath && '/' == *xpath && *(xpath+1) != '/')
  6242. throw MakeXPathException(xpath, PTreeExcpt_XPath_Unsupported, 0, "Root specifier \"/\" specifier is not supported");
  6243. _validateXPathSyntax(xpath);
  6244. return true;
  6245. }
  6246. catch (IException *e)
  6247. {
  6248. if (error)
  6249. e->errorMessage(*error);
  6250. e->Release();
  6251. return false;
  6252. }
  6253. }
  6254. static bool isContentXPath(const char *xpath, StringBuffer &head)
  6255. {
  6256. unsigned l = xpath?strlen(xpath):0;
  6257. const char *x = xpath+l-2;
  6258. if (l>=2 && 0==strcmp(XMLTAG_CONTENT, x))
  6259. {
  6260. if (x != xpath)
  6261. head.append(x-xpath, xpath);
  6262. return true;
  6263. }
  6264. return false;
  6265. }
  6266. bool validateXMLParseXPath(const char *xpath, StringBuffer *error)
  6267. {
  6268. if (!xpath || !*xpath)
  6269. return true;
  6270. StringBuffer head;
  6271. if (isContentXPath(xpath, head))
  6272. {
  6273. if (head.length())
  6274. {
  6275. if ('/' == *xpath && '/' != *(xpath+1))
  6276. {
  6277. if (error)
  6278. {
  6279. Owned<IException> e = MakeStringException(0, "Invalid extract xml text '<>' usage, xpath cannot from be absolute: %s", xpath);
  6280. e->errorMessage(*error);
  6281. }
  6282. return false;
  6283. }
  6284. return validateXPathSyntax(head.str(), error);
  6285. }
  6286. return true;
  6287. }
  6288. else
  6289. return validateXPathSyntax('/' == *xpath && '/' != *(xpath+1) ? xpath+1 : xpath, error);
  6290. return true;
  6291. }
  6292. bool areMatchingPTrees(const IPropertyTree * left, const IPropertyTree * right)
  6293. {
  6294. if (left == right)
  6295. return true;
  6296. if (!left || !right)
  6297. return false;
  6298. bool isCaseInsensitive = left->isCaseInsensitive();
  6299. const char * lname = left->queryName();
  6300. const char * rname = right->queryName();
  6301. if (!lname || !rname)
  6302. {
  6303. if (lname || rname)
  6304. return false;
  6305. }
  6306. else if ((isCaseInsensitive ? stricmp(lname, rname) : strcmp(lname, rname)) != 0)
  6307. return false;
  6308. Owned<IAttributeIterator> leftAttrIter = left->getAttributes(true);
  6309. Owned<IAttributeIterator> rightAttrIter = right->getAttributes(true);
  6310. rightAttrIter->first();
  6311. ForEach(*leftAttrIter)
  6312. {
  6313. if (!rightAttrIter->isValid()) return false;
  6314. const char * lname = leftAttrIter->queryName();
  6315. const char * rname = rightAttrIter->queryName();
  6316. if ((isCaseInsensitive ? stricmp(lname, rname) : strcmp(lname, rname)) != 0)
  6317. return false;
  6318. if (strcmp(leftAttrIter->queryValue(), rightAttrIter->queryValue()) != 0)
  6319. return false;
  6320. rightAttrIter->next();
  6321. }
  6322. if (rightAttrIter->isValid()) return false;
  6323. Owned<IPropertyTreeIterator> leftElemIter = left->getElements("*", iptiter_sort);
  6324. Owned<IPropertyTreeIterator> rightElemIter = right->getElements("*", iptiter_sort);
  6325. rightElemIter->first();
  6326. ForEach(*leftElemIter)
  6327. {
  6328. if (!rightElemIter->isValid()) return false;
  6329. if (!areMatchingPTrees(&leftElemIter->query(), &rightElemIter->query()))
  6330. return false;
  6331. rightElemIter->next();
  6332. }
  6333. if (rightElemIter->isValid()) return false;
  6334. return true;
  6335. }
  6336. /////////////////////
  6337. static const char * skipWhitespace(const char * text)
  6338. {
  6339. while ((*text==' ') || (*text=='\t'))
  6340. text++;
  6341. return text;
  6342. }
  6343. static const char * skipAsterisk(const char * text)
  6344. {
  6345. if (*text=='*')
  6346. return skipWhitespace(text+1);
  6347. return text;
  6348. }
  6349. static const char * skipToNewline(const char * text)
  6350. {
  6351. while (*text && (*text != '\r') && (*text != '\n'))
  6352. text++;
  6353. return text;
  6354. }
  6355. static const char * skipNewline(const char * text)
  6356. {
  6357. if (*text == '\r')
  6358. text++;
  6359. if (*text == '\n')
  6360. text++;
  6361. return text;
  6362. }
  6363. void extractJavadoc(IPropertyTree * result, const char * text)
  6364. {
  6365. //Skip a leading blank line
  6366. text = skipWhitespace(text);
  6367. text = skipNewline(text);
  6368. //Now process each of the parameters...
  6369. StringBuffer tagname;
  6370. StringBuffer tagtext;
  6371. for (;;)
  6372. {
  6373. text = skipWhitespace(text);
  6374. text = skipAsterisk(text);
  6375. if ((*text == 0) || (*text == '@'))
  6376. {
  6377. if (tagtext.length())
  6378. {
  6379. if (tagname.length())
  6380. result->addProp(tagname.str(), tagtext.str());
  6381. else
  6382. result->setProp("", tagtext.str());
  6383. tagtext.clear();
  6384. }
  6385. if (*text == 0)
  6386. return;
  6387. text++;
  6388. const char * start = text;
  6389. while (isalnum(*text))
  6390. text++;
  6391. if (start != text)
  6392. tagname.clear().append(text-start, start);
  6393. text = skipWhitespace(text);
  6394. }
  6395. const char * start = text;
  6396. text = skipToNewline(text);
  6397. if (start != text)
  6398. {
  6399. if (tagtext.length())
  6400. tagtext.append(" ");
  6401. tagtext.append(text-start, start);
  6402. }
  6403. text = skipNewline(text);
  6404. }
  6405. }
  6406. /////////////////////
  6407. #ifdef _DEBUG
  6408. jlib_decl void validatePTree()
  6409. {
  6410. Owned<IPropertyTree> testTree = createPTreeFromXMLString(
  6411. "<ROOT>" \
  6412. " <E a=\"av1\" b=\"bv1\" c=\"cv1\"></E>" \
  6413. " <E a=\"av1\" b=\"bv1\" c=\"cv2\"></E>" \
  6414. " <E a=\"av2\" b=\"bv1\"></E>" \
  6415. " <SE c=\"cv1\"></SE>" \
  6416. " <E a=\"av1\" b=\"bv2\"></E>" \
  6417. " <E a=\"av2\" b=\"bv2\" c=\"cv3\">ev1</E>" \
  6418. "</ROOT>"
  6419. );
  6420. Owned<IPropertyTreeIterator> iter = testTree->getElements("E[@a=\"av1\"][@b=\"bv2\"]");
  6421. unsigned c = 0;
  6422. ForEach (*iter)
  6423. ++c;
  6424. assertex(1 == c);
  6425. int v = strcmp("bv1", testTree->queryProp("E[@a=\"av1\"][2]/@b"));
  6426. assertex(0 == v);
  6427. v = strcmp("cv2", testTree->queryProp("E[@a=\"av1\"][@b=\"bv1\"][2]/@c"));
  6428. assertex(0 == v);
  6429. v = strcmp("cv2", testTree->queryProp("E[@a=\"av1\"][2]/@c"));
  6430. assertex(0 == v);
  6431. v = strcmp("ev1", testTree->queryProp("E[@a=\"av2\"][@c]"));
  6432. assertex(0 == v);
  6433. }
  6434. jlib_decl void testValidateXPathSyntax()
  6435. {
  6436. verifyex(validateXPathSyntax("@abc"));
  6437. verifyex(validateXPathSyntax("prop"));
  6438. verifyex(validateXPathSyntax("a/b"));
  6439. verifyex(validateXPathSyntax("a/@b"));
  6440. const char *s = "a[@a=\"blah\"]/b";
  6441. verifyex(validateXPathSyntax(s));
  6442. s = "a/b[@b=\"blah\"]";
  6443. verifyex(validateXPathSyntax(s));
  6444. verifyex(validateXPathSyntax(s));
  6445. s = "a/b[b=\"blah\"]";
  6446. verifyex(validateXPathSyntax(s));
  6447. s = "a/b[a/b=\"blah\"]";
  6448. verifyex(validateXPathSyntax(s));
  6449. verifyex(validateXPathSyntax("a[1]/b[2]"));
  6450. s = "a[b]/b[c=\"a\"]/c";
  6451. verifyex(validateXPathSyntax(s));
  6452. verifyex(validateXPathSyntax("//a/b/c"));
  6453. verifyex(!validateXPathSyntax("a[b"));
  6454. verifyex(!validateXPathSyntax("a["));
  6455. verifyex(!validateXPathSyntax("a]"));
  6456. verifyex(!validateXPathSyntax("a[b=blah]"));
  6457. verifyex(!validateXPathSyntax("@a/b"));
  6458. verifyex(!validateXPathSyntax("a[b[c]]"));
  6459. verifyex(validateXMLParseXPath("<>"));
  6460. verifyex(validateXMLParseXPath("a/b/c<>"));
  6461. verifyex(validateXMLParseXPath("a/b/<>"));
  6462. verifyex(validateXMLParseXPath("/a/b"));
  6463. verifyex(!validateXMLParseXPath("a/b[\"]/<>"));
  6464. verifyex(!validateXMLParseXPath("/<>"));
  6465. }
  6466. jlib_decl void testJdocCompare()
  6467. {
  6468. Owned<IPropertyTree> t1 = createPTree();
  6469. Owned<IPropertyTree> t2 = createPTree();
  6470. Owned<IPropertyTree> t3 = createPTree();
  6471. Owned<IPropertyTree> t4 = createPTree();
  6472. Owned<IPropertyTree> t5 = createPTree();
  6473. extractJavadoc(t1, "Defines a record that contains information about a person");
  6474. extractJavadoc(t2, "Allows the name table to be filtered.\n\n@param ages\tThe ages that are allowed to be processed.\n\t\tbadForename Forname to avoid.\n\n@return\tthe filtered dataset.");
  6475. extractJavadoc(t3, "Allows the name table to be filtered.\n\n@param ages\tThe ages that are allowed to be processed.\n\t\tbadForename Forname to avoid.\n\n@return\tthe filtered dataset.");
  6476. extractJavadoc(t4, "Allows the name table to be filtered.\n\n@param ages\tThe ages that are allowed to be processed.\n\t\tbadForename Forname to avoid.\n\n@return\tthe filtered dataset.");
  6477. extractJavadoc(t5, "Allows the name table to be filtered.\n\n@param ages\tThe ages that are allowed to be processed.\n\t\tbadForename Forname to avoid.\n\n@return\tthe filtered dataset.");
  6478. IPropertyTree * t2c = t2->addPropTree("Child1", createPTree());
  6479. extractJavadoc(t2c, "This is some child data\n\n@param ages\tThe ages that are allowed to be processed.");
  6480. IPropertyTree * t3c = t3->addPropTree("Child1", createPTree());
  6481. extractJavadoc(t3c, "This is some child data\n\n@param ages\tThe ages that are allowed to be processed.");
  6482. IPropertyTree * t4c = t4->addPropTree("Child1", createPTree());
  6483. extractJavadoc(t4c, "This is some child data\n\n@param ages\tThe ages that are allowed to be processed, but differs.");
  6484. IPropertyTree * t5c = t5->addPropTree("Child1", createPTree());
  6485. extractJavadoc(t5c, "This is some child data\n\n@param ages\tThe ages that are allowed to be processed.");
  6486. t2->setProp("@childAttr", "1");
  6487. t3->setProp("@childAttr", "1");
  6488. t4->setProp("@childAttr", "1");
  6489. t5->setProp("@childAttr", "2");
  6490. verifyex(areMatchingPTrees(NULL, NULL));
  6491. verifyex(!areMatchingPTrees(NULL, t1));
  6492. verifyex(!areMatchingPTrees(t1, NULL));
  6493. verifyex(areMatchingPTrees(t1, t1));
  6494. verifyex(areMatchingPTrees(t2, t3));
  6495. verifyex(!areMatchingPTrees(t2, t4));
  6496. verifyex(!areMatchingPTrees(t2, t5));
  6497. }
  6498. #endif
  6499. template <class BASE_PTREE>
  6500. class COrderedPTree : public BASE_PTREE
  6501. {
  6502. template <class BASECHILDMAP>
  6503. class jlib_decl COrderedChildMap : public BASECHILDMAP
  6504. {
  6505. typedef COrderedChildMap<BASECHILDMAP> SELF;
  6506. ICopyArrayOf<IPropertyTree> order;
  6507. public:
  6508. IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(IPropertyTree, constcharptr);
  6509. COrderedChildMap<BASECHILDMAP>() : BASECHILDMAP() { }
  6510. ~COrderedChildMap<BASECHILDMAP>() { SELF::kill(); }
  6511. virtual unsigned numChildren() override { return order.ordinality(); }
  6512. virtual IPropertyTreeIterator *getIterator(bool sort) override
  6513. {
  6514. class CPTArrayIterator : public ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>
  6515. {
  6516. IArrayOf<IPropertyTree> elems;
  6517. public:
  6518. CPTArrayIterator(ICopyArrayOf<IPropertyTree> &order, bool sort) : ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>(elems)
  6519. {
  6520. ForEachItemIn(e, order)
  6521. elems.append(*LINK(&order.item(e)));
  6522. if (sort)
  6523. elems.sort(comparePropTrees);
  6524. }
  6525. };
  6526. return new CPTArrayIterator(order, sort);
  6527. }
  6528. virtual bool set(const char *key, IPropertyTree *tree) override
  6529. {
  6530. IPropertyTree *existing = find(*key);
  6531. if (existing)
  6532. {
  6533. unsigned pos = order.find(*existing);
  6534. BASECHILDMAP::set(key, tree);
  6535. order.replace(*tree, pos);
  6536. }
  6537. else
  6538. {
  6539. BASECHILDMAP::set(key, tree);
  6540. order.append(*tree);
  6541. }
  6542. return true;
  6543. }
  6544. virtual bool replace(const char *key, IPropertyTree *tree) override // provides different semantics, used if element being replaced is not to be treated as deleted.
  6545. {
  6546. return set(key, tree);
  6547. }
  6548. virtual bool remove(const char *key) override
  6549. {
  6550. IPropertyTree *child = BASECHILDMAP::find(*key);
  6551. if (!child)
  6552. return false;
  6553. order.zap(*child);
  6554. return BASECHILDMAP::removeExact(child);
  6555. }
  6556. virtual bool removeExact(IPropertyTree *child) override
  6557. {
  6558. order.zap(*child);
  6559. return BASECHILDMAP::removeExact(child);
  6560. }
  6561. };
  6562. public:
  6563. typedef COrderedPTree<BASE_PTREE> SELF;
  6564. COrderedPTree<BASE_PTREE>(const char *name=NULL, byte flags=ipt_none, IPTArrayValue *value=NULL, ChildMap *children=NULL)
  6565. : BASE_PTREE(name, flags|ipt_ordered, value, children) { }
  6566. virtual bool isEquivalent(IPropertyTree *tree) const override { return (NULL != QUERYINTERFACE(tree, COrderedPTree<BASE_PTREE>)); }
  6567. virtual IPropertyTree *create(const char *name=NULL, IPTArrayValue *value=NULL, ChildMap *children=NULL, bool existing=false) override
  6568. {
  6569. return new COrderedPTree<BASE_PTREE>(name, SELF::flags, value, children);
  6570. }
  6571. virtual IPropertyTree *create(MemoryBuffer &mb) override
  6572. {
  6573. IPropertyTree *tree = new COrderedPTree<BASE_PTREE>();
  6574. tree->deserialize(mb);
  6575. return tree;
  6576. }
  6577. virtual void createChildMap() override
  6578. {
  6579. if (SELF::isnocase())
  6580. SELF::children = new COrderedChildMap<ChildMapNC>();
  6581. else
  6582. SELF::children = new COrderedChildMap<ChildMap>();
  6583. }
  6584. };
  6585. IPropertyTree *createPTree(byte flags)
  6586. {
  6587. return createPTree(NULL, flags);
  6588. }
  6589. IPropertyTree *createPTree(const char *name, byte flags)
  6590. {
  6591. switch (flags & (ipt_ordered|ipt_fast|ipt_lowmem))
  6592. {
  6593. case ipt_ordered|ipt_fast:
  6594. return new COrderedPTree<LocalPTree>(name, flags);
  6595. case ipt_ordered|ipt_lowmem:
  6596. return new COrderedPTree<CAtomPTree>(name, flags);
  6597. case ipt_ordered:
  6598. return new COrderedPTree<DEFAULT_PTREE_TYPE>(name, flags);
  6599. case ipt_fast:
  6600. return new LocalPTree(name, flags);
  6601. case ipt_lowmem:
  6602. return new CAtomPTree(name, flags);
  6603. case 0:
  6604. return new DEFAULT_PTREE_TYPE(name, flags);
  6605. default:
  6606. throwUnexpectedX("Invalid flags - ipt_fast and ipt_lowmem should not be specified together");
  6607. }
  6608. }
  6609. typedef enum _ptElementType
  6610. {
  6611. elementTypeUnknown,
  6612. elementTypeNull,
  6613. elementTypeString,
  6614. elementTypeBool,
  6615. elementTypeInteger,
  6616. elementTypeReal,
  6617. elementTypeObject,
  6618. elementTypeArray
  6619. } ptElementType;
  6620. template <typename X>
  6621. class CJSONReaderBase : public CommonReaderBase<X>
  6622. {
  6623. public:
  6624. typedef CommonReaderBase<X> PARENT;
  6625. using PARENT::reset;
  6626. using PARENT::nextChar;
  6627. using PARENT::readNextToken;
  6628. using PARENT::checkReadNext;
  6629. using PARENT::checkStartReadNext;
  6630. using PARENT::readNext;
  6631. using PARENT::expecting;
  6632. using PARENT::match;
  6633. using PARENT::error;
  6634. using PARENT::skipWS;
  6635. using PARENT::rewind;
  6636. using PARENT::ignoreWhiteSpace;
  6637. CJSONReaderBase(ISimpleReadStream &_stream, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions, size32_t _bufSize=0) :
  6638. CommonReaderBase<X>(_stream, _iEvent, _readerOptions, _bufSize)
  6639. {
  6640. }
  6641. CJSONReaderBase(const void *_buf, size32_t bufLength, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
  6642. CommonReaderBase<X>(_buf, bufLength, _iEvent, _readerOptions)
  6643. {
  6644. }
  6645. CJSONReaderBase(const void *_buf, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
  6646. CommonReaderBase<X>(_buf, _iEvent, _readerOptions)
  6647. {
  6648. }
  6649. ~CJSONReaderBase()
  6650. {
  6651. }
  6652. protected:
  6653. inline StringBuffer &appendChar(StringBuffer &id, char c)
  6654. {
  6655. int charlen = validJSONUtf8ChrLen(c);
  6656. if (!charlen)
  6657. error("invalid JSON character", true);
  6658. id.append(nextChar);
  6659. while (--charlen)
  6660. {
  6661. readNext();
  6662. id.append(nextChar);
  6663. }
  6664. return id;
  6665. }
  6666. void readString(StringBuffer &value)
  6667. {
  6668. readNext();
  6669. StringBuffer s;
  6670. bool decode=false;
  6671. while ('\"'!=nextChar)
  6672. {
  6673. if (nextChar=='\\')
  6674. decode=true;
  6675. appendChar(s, nextChar);
  6676. readNext();
  6677. }
  6678. size32_t r = s.length();
  6679. if (ignoreWhiteSpace)
  6680. s.trimRight();
  6681. if (decode)
  6682. _decodeJSON(r, s.str(), value, s.length()+1);
  6683. else
  6684. value.swapWith(s);
  6685. }
  6686. void readName(StringBuffer &name)
  6687. {
  6688. if ('\"'!=nextChar)
  6689. expecting("\"");
  6690. readString(name);
  6691. if (!name.length())
  6692. error("empty JSON id");
  6693. readNext();
  6694. skipWS();
  6695. if (':'!=nextChar)
  6696. expecting(":");
  6697. readNext();
  6698. }
  6699. ptElementType readValue(StringBuffer &value)
  6700. {
  6701. ptElementType type = elementTypeUnknown;
  6702. switch (nextChar)
  6703. {
  6704. case '\"':
  6705. {
  6706. readString(value);
  6707. type = elementTypeString;
  6708. break;
  6709. }
  6710. case 't':
  6711. match("rue", "Bad value");
  6712. value.append("true");
  6713. type = elementTypeBool;
  6714. break;
  6715. case 'f':
  6716. match("alse", "Bad value");
  6717. value.append("false");
  6718. type = elementTypeBool;
  6719. break;
  6720. case 'n':
  6721. match("ull", "Bad value");
  6722. type = elementTypeNull;
  6723. break;
  6724. case '-':
  6725. value.append(nextChar);
  6726. readNext();
  6727. //fall through
  6728. default:
  6729. if (!isdigit(nextChar))
  6730. error("Bad value");
  6731. type = elementTypeInteger;
  6732. bool exponent = false;
  6733. while (isdigit(nextChar) || '.'==nextChar || 'e'==nextChar || 'E'==nextChar)
  6734. {
  6735. if ('e'==nextChar || 'E'==nextChar)
  6736. {
  6737. if (exponent)
  6738. error("Bad value");
  6739. exponent=true;
  6740. value.append(nextChar);
  6741. readNext();
  6742. if ('-'==nextChar)
  6743. type=elementTypeReal;
  6744. else if (!isdigit(nextChar) && '+'!=nextChar)
  6745. error("Bad value");
  6746. }
  6747. if ('.'==nextChar)
  6748. {
  6749. if (exponent || type==elementTypeReal) //already found decimal
  6750. error("Bad value");
  6751. type = elementTypeReal;
  6752. }
  6753. value.append(nextChar);
  6754. readNext();
  6755. }
  6756. rewind(1);
  6757. break;
  6758. }
  6759. return type;
  6760. }
  6761. const char *_decodeJSON(unsigned read, const char *startMark, StringBuffer &ret, unsigned len)
  6762. {
  6763. const char *errMark = NULL;
  6764. try { return decodeJSON(startMark, ret, len, &errMark); }
  6765. catch (IException *e)
  6766. {
  6767. if (errMark)
  6768. {
  6769. if (read>(unsigned)(errMark-startMark))
  6770. rewind((unsigned)(read - (errMark-startMark)));
  6771. else
  6772. rewind((unsigned)(errMark-startMark));
  6773. }
  6774. StringBuffer errMsg;
  6775. e->errorMessage(errMsg);
  6776. e->Release();
  6777. error(errMsg.str());
  6778. }
  6779. return NULL; // will never get here.
  6780. }
  6781. };
  6782. template <class X>
  6783. class CJSONReader : public CJSONReaderBase<X>, implements IPTreeReader
  6784. {
  6785. typedef CJSONReaderBase<X> PARENT;
  6786. using PARENT::checkBOM;
  6787. using PARENT::rewind;
  6788. using PARENT::readNext;
  6789. using PARENT::readValue;
  6790. using PARENT::readName;
  6791. using PARENT::checkReadNext;
  6792. using PARENT::checkSkipWS;
  6793. using PARENT::checkStartReadNext;
  6794. using PARENT::expecting;
  6795. using PARENT::error;
  6796. using PARENT::eos;
  6797. using PARENT::_decodeJSON;
  6798. using PARENT::skipWS;
  6799. using PARENT::nextChar;
  6800. using PARENT::curOffset;
  6801. using PARENT::noRoot;
  6802. using PARENT::ignoreWhiteSpace;
  6803. using PARENT::iEvent;
  6804. // StringBuffer tmpStr;
  6805. public:
  6806. IMPLEMENT_IINTERFACE;
  6807. CJSONReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize=0)
  6808. : PARENT(stream, iEvent, readerOptions, bufSize)
  6809. {
  6810. }
  6811. CJSONReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  6812. : PARENT(buf, bufLength, iEvent, readerOptions)
  6813. {
  6814. }
  6815. CJSONReader(const void *buf, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  6816. : PARENT(buf, iEvent, readerOptions)
  6817. {
  6818. }
  6819. void readValueNotify(const char *name, bool skipAttributes, StringBuffer *retValue, bool *isValueBinary)
  6820. {
  6821. offset_t startOffset = curOffset;
  6822. StringBuffer value;
  6823. if (readValue(value)==elementTypeNull)
  6824. return;
  6825. if ('@'==*name)
  6826. {
  6827. if (!skipAttributes)
  6828. iEvent->newAttribute(name, value.str());
  6829. return;
  6830. }
  6831. else if ('#'==*name)
  6832. {
  6833. dbgassertex(retValue && isValueBinary);
  6834. *isValueBinary = false;
  6835. if (0 == strncmp(name+1, "value", 5)) // this is a special IPT JSON prop name, representing a 'complex' value
  6836. {
  6837. if ('\0' == *(name+6)) // #value
  6838. {
  6839. retValue->swapWith(value);
  6840. return;
  6841. }
  6842. else if (streq(name+6, "bin")) // #valuebin
  6843. {
  6844. *isValueBinary = true;
  6845. JBASE64_Decode(value.str(), *retValue);
  6846. return;
  6847. }
  6848. }
  6849. }
  6850. iEvent->beginNode(name, false, startOffset);
  6851. iEvent->beginNodeContent(name);
  6852. iEvent->endNode(name, value.length(), value.str(), false, curOffset);
  6853. }
  6854. void readArray(const char *name)
  6855. {
  6856. if ('@'==*name)
  6857. name++;
  6858. readNext();
  6859. skipWS();
  6860. while (']' != nextChar)
  6861. {
  6862. switch (nextChar)
  6863. {
  6864. case '[':
  6865. iEvent->beginNode(name, false, curOffset);
  6866. iEvent->beginNodeContent(name);
  6867. readArray(name);
  6868. iEvent->endNode(name, 0, "", false, curOffset);
  6869. break;
  6870. case '{':
  6871. readObject(name);
  6872. break;
  6873. default:
  6874. readValueNotify(name, true, nullptr, nullptr);
  6875. break;
  6876. }
  6877. readNext();
  6878. skipWS();
  6879. if (','==nextChar)
  6880. readNext();
  6881. else if (']'!=nextChar)
  6882. error("expected ',' or ']'");
  6883. skipWS();
  6884. }
  6885. }
  6886. void readChild(const char *name, bool skipAttributes, StringBuffer *value, bool *isValueBinary)
  6887. {
  6888. skipWS();
  6889. switch (nextChar)
  6890. {
  6891. case '}':
  6892. {
  6893. VStringBuffer msg("named item with no value defined %s [%d]", name, (int) curOffset);
  6894. error(msg.str());
  6895. }
  6896. break;
  6897. case '{':
  6898. readObject(name);
  6899. break;
  6900. case '[':
  6901. readArray(name);
  6902. break;
  6903. default:
  6904. readValueNotify(name, skipAttributes, value, isValueBinary);
  6905. break;
  6906. }
  6907. }
  6908. void readObject(const char *name)
  6909. {
  6910. if ('@'==*name)
  6911. name++;
  6912. iEvent->beginNode(name, false, curOffset);
  6913. readNext();
  6914. skipWS();
  6915. bool attributesFinalized=false;
  6916. StringBuffer childValue; // for #value
  6917. bool isChildValueBinary = false; // for #value
  6918. while ('}' != nextChar)
  6919. {
  6920. StringBuffer tagName;
  6921. readName(tagName);
  6922. //internal convention so we can convert to and from xml
  6923. //values at top of object with names starting with '@' become ptree attributes
  6924. if (*tagName.str()!='@')
  6925. attributesFinalized=true;
  6926. readChild(tagName.str(), attributesFinalized, &childValue.clear(), &isChildValueBinary);
  6927. readNext();
  6928. skipWS();
  6929. if (','==nextChar)
  6930. readNext();
  6931. else if ('}'!=nextChar)
  6932. error("expected ',' or '}'");
  6933. skipWS();
  6934. }
  6935. iEvent->endNode(name, childValue.length(), childValue.str(), isChildValueBinary, curOffset);
  6936. }
  6937. void loadJSON()
  6938. {
  6939. if (!checkStartReadNext())
  6940. return;
  6941. if (checkBOM() && !checkReadNext())
  6942. return;
  6943. if (!checkSkipWS())
  6944. return;
  6945. if (noRoot)
  6946. {
  6947. StringBuffer tagName;
  6948. for (;;)
  6949. {
  6950. switch (nextChar)
  6951. {
  6952. case '\"': //treat named objects like we're in a noroot object
  6953. readName(tagName.clear());
  6954. readChild(tagName.str(), true, nullptr, nullptr);
  6955. break;
  6956. case '{': //treat unnamed objects like we're in a noroot array
  6957. readObject("__object__");
  6958. break;
  6959. case '[': //treat unnamed arrays like we're in a noroot array
  6960. iEvent->beginNode("__array__", false, curOffset);
  6961. readArray("__item__");
  6962. iEvent->endNode("__array__", 0, "", false, curOffset);
  6963. break;
  6964. default:
  6965. expecting("{[ or \"");
  6966. }
  6967. if (!checkReadNext() || !checkSkipWS())
  6968. break;
  6969. switch (nextChar)
  6970. {
  6971. case '{': //support file formats with whitespace (usually \n) seperated objects at the root
  6972. case '[':
  6973. break;
  6974. case ',':
  6975. readNext();
  6976. skipWS();
  6977. break;
  6978. default:
  6979. expecting(",");
  6980. break;
  6981. }
  6982. }
  6983. }
  6984. else
  6985. {
  6986. if ('{' == nextChar)
  6987. readObject("__object__");
  6988. else if ('[' == nextChar)
  6989. {
  6990. iEvent->beginNode("__array__", false, curOffset);
  6991. readArray("__item__");
  6992. iEvent->endNode("__array__", 0, "", false, curOffset);
  6993. }
  6994. else
  6995. error("expected '{' or '['");
  6996. if (checkReadNext() && checkSkipWS())
  6997. error("trailing content after JSON closed");
  6998. }
  6999. }
  7000. // IPTreeReader
  7001. virtual void load() { loadJSON(); }
  7002. virtual offset_t queryOffset() { return curOffset; }
  7003. };
  7004. template <class X>
  7005. class CPullJSONReader : public CJSONReaderBase<X>, implements IPullPTreeReader
  7006. {
  7007. typedef CJSONReaderBase<X> PARENT;
  7008. using PARENT::checkBOM;
  7009. using PARENT::rewind;
  7010. using PARENT::readNext;
  7011. using PARENT::readValue;
  7012. using PARENT::readName;
  7013. using PARENT::checkReadNext;
  7014. using PARENT::checkSkipWS;
  7015. using PARENT::checkStartReadNext;
  7016. using PARENT::expecting;
  7017. using PARENT::error;
  7018. using PARENT::eos;
  7019. using PARENT::_decodeJSON;
  7020. using PARENT::skipWS;
  7021. using PARENT::nextChar;
  7022. using PARENT::curOffset;
  7023. using PARENT::noRoot;
  7024. using PARENT::ignoreWhiteSpace;
  7025. using PARENT::iEvent;
  7026. class CStateInfo : public CInterface
  7027. {
  7028. public:
  7029. CStateInfo()
  7030. {
  7031. tag.ensureCapacity(15);
  7032. type = elementTypeUnknown;
  7033. childCount = 0;
  7034. wnsTag = NULL;
  7035. }
  7036. inline void reset()
  7037. {
  7038. wnsTag = NULL;
  7039. tag.clear();
  7040. tagText.clear();
  7041. type = elementTypeUnknown;
  7042. childCount = 0;
  7043. }
  7044. StringBuffer tag;
  7045. StringBuffer tagText;
  7046. ptElementType type;
  7047. const char *wnsTag;
  7048. unsigned childCount;
  7049. };
  7050. CICopyArrayOf<CStateInfo> stack, freeStateInfo;
  7051. CStateInfo *stateInfo;
  7052. enum ParseStates { headerStart, nameStart, valueStart, itemStart, objAttributes, itemContent, itemEnd } state;
  7053. bool endOfRoot;
  7054. bool preReadItemName;
  7055. bool more;
  7056. StringBuffer tag, value;
  7057. void init()
  7058. {
  7059. state = headerStart;
  7060. stateInfo = NULL;
  7061. endOfRoot = false;
  7062. preReadItemName = false;
  7063. more = true;
  7064. }
  7065. virtual void resetState()
  7066. {
  7067. stack.kill();
  7068. more = true;
  7069. }
  7070. public:
  7071. IMPLEMENT_IINTERFACE;
  7072. CPullJSONReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize=0)
  7073. : CJSONReaderBase<X>(stream, iEvent, readerOptions, bufSize)
  7074. {
  7075. init();
  7076. }
  7077. CPullJSONReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  7078. : CJSONReaderBase<X>(buf, bufLength, iEvent, readerOptions)
  7079. {
  7080. init();
  7081. }
  7082. CPullJSONReader(const void *buf, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  7083. : CJSONReaderBase<X>(buf, iEvent, readerOptions)
  7084. {
  7085. init();
  7086. }
  7087. ~CPullJSONReader()
  7088. {
  7089. ForEachItemIn(i, stack)
  7090. delete &stack.item(i);
  7091. ForEachItemIn(i2, freeStateInfo)
  7092. delete &freeStateInfo.item(i2);
  7093. }
  7094. inline void checkDelimiter(const char *msg=",")
  7095. {
  7096. if (stateInfo && stateInfo->childCount > 0)
  7097. {
  7098. if (','!=nextChar)
  7099. expecting(msg);
  7100. readNext();
  7101. skipWS();
  7102. }
  7103. }
  7104. inline ptElementType getParentType()
  7105. {
  7106. if (stack.ordinality()<2)
  7107. return stateInfo->type;
  7108. return ((CStateInfo *)&stack.tos(1))->type;
  7109. }
  7110. void beginNode(const char *name, offset_t offset, ptElementType jsonType, bool notify=true)
  7111. {
  7112. if (stateInfo)
  7113. stateInfo->childCount++;
  7114. if (freeStateInfo.ordinality())
  7115. {
  7116. stateInfo = &freeStateInfo.popGet();
  7117. stateInfo->reset();
  7118. }
  7119. else
  7120. stateInfo = new CStateInfo;
  7121. stack.append(*stateInfo);
  7122. stateInfo->type=jsonType;
  7123. if (name)
  7124. stateInfo->tag.set(name);
  7125. else
  7126. stateInfo->tag.swapWith(tag);
  7127. stateInfo->wnsTag = stateInfo->tag.str();
  7128. if (!notify)
  7129. return;
  7130. try
  7131. {
  7132. iEvent->beginNode(stateInfo->wnsTag, false, offset);
  7133. }
  7134. catch (IPTreeException *pe)
  7135. {
  7136. if (PTreeExcpt_InvalidTagName == pe->errorCode())
  7137. {
  7138. pe->Release();
  7139. StringBuffer msg("Expecting valid start tag, but got \"");
  7140. error(msg.append(name).append("\"").str());
  7141. }
  7142. throw;
  7143. }
  7144. }
  7145. inline const char *arrayItemName(const char *defaultName)
  7146. {
  7147. if (stack.ordinality()>1)
  7148. return stateInfo->wnsTag;
  7149. return defaultName;
  7150. }
  7151. bool arrayItem(offset_t offset)
  7152. {
  7153. skipWS();
  7154. switch (nextChar)
  7155. {
  7156. case ']':
  7157. state=itemContent;
  7158. if (stack.ordinality()>1)
  7159. readNext();
  7160. if (!endNode(curOffset, getParentType()==elementTypeArray))
  7161. return false;
  7162. break;
  7163. case '{':
  7164. state=objAttributes;
  7165. readNext();
  7166. beginNode(arrayItemName("__object__"), offset, elementTypeObject);
  7167. break;
  7168. case '[':
  7169. state=valueStart;
  7170. readNext();
  7171. beginNode(arrayItemName("__array__"), offset, elementTypeArray, true);
  7172. break;
  7173. default:
  7174. state=valueStart;
  7175. ptElementType type = readValue(value.clear());
  7176. readNext();
  7177. beginNode(arrayItemName("__item__"), offset, type, true);
  7178. stateInfo->tagText.swapWith(value);
  7179. break;
  7180. }
  7181. return true;
  7182. }
  7183. void namedItem()
  7184. {
  7185. if (!preReadItemName)
  7186. readName(tag.clear());
  7187. else
  7188. preReadItemName = false;
  7189. skipWS();
  7190. switch (nextChar)
  7191. {
  7192. case '}':
  7193. error("unexpected object close marker");
  7194. case ']':
  7195. error("unexpected array close marker");
  7196. case '{':
  7197. state=objAttributes;
  7198. readNext();
  7199. beginNode(NULL, curOffset, elementTypeObject);
  7200. break;
  7201. case '[':
  7202. readNext();
  7203. beginNode(NULL, curOffset, elementTypeArray, false); //false because items present events, not the array
  7204. arrayItem(curOffset); //so process the first item so every next() has event
  7205. break;
  7206. default:
  7207. state=valueStart;
  7208. ptElementType type = readValue(value.clear());
  7209. readNext();
  7210. beginNode(NULL, curOffset, type);
  7211. stateInfo->tagText.swapWith(value);
  7212. break;
  7213. }
  7214. }
  7215. void rootItem()
  7216. {
  7217. if ('\"'==nextChar)
  7218. namedItem();
  7219. else if ('{'==nextChar || '['==nextChar)
  7220. arrayItem(curOffset);
  7221. else
  7222. expecting("[{ or \"");
  7223. }
  7224. bool rootNext()
  7225. {
  7226. if (!noRoot)
  7227. return false;
  7228. if (!checkReadNext() || !checkSkipWS())
  7229. return true;
  7230. switch (nextChar)
  7231. {
  7232. case '{': //support files where root level objects are separated by whitespace (usually \n)
  7233. case '[':
  7234. case ',':
  7235. break;
  7236. default:
  7237. expecting(",");
  7238. }
  7239. return true;
  7240. }
  7241. void newNamedAttribute()
  7242. {
  7243. skipWS();
  7244. readValue(value.clear());
  7245. readNext();
  7246. stateInfo->childCount++;
  7247. iEvent->newAttribute(tag.str(), value.str());
  7248. }
  7249. bool endNode(offset_t offset, bool notify=true)
  7250. {
  7251. if (stack.ordinality()<2)
  7252. {
  7253. state = headerStart;
  7254. more = rootNext();
  7255. }
  7256. if (notify)
  7257. {
  7258. if (stateInfo->type==elementTypeNull)
  7259. iEvent->endNode(stateInfo->wnsTag, 0, "", false, offset);
  7260. else
  7261. iEvent->endNode(stateInfo->wnsTag, stateInfo->tagText.length(), stateInfo->tagText.str(), false, offset);
  7262. }
  7263. freeStateInfo.append(*stateInfo);
  7264. stack.pop();
  7265. stateInfo = (stack.ordinality()) ? &stack.tos() : NULL;
  7266. return true;
  7267. }
  7268. // IPullPTreeReader
  7269. virtual void load()
  7270. {
  7271. while (next()) {}
  7272. }
  7273. virtual void reset()
  7274. {
  7275. PARENT::reset();
  7276. resetState();
  7277. }
  7278. virtual offset_t queryOffset() { return curOffset; }
  7279. virtual bool next()
  7280. {
  7281. if (!more)
  7282. return false;
  7283. checkStartReadNext();
  7284. checkSkipWS();
  7285. switch (state)
  7286. {
  7287. case headerStart:
  7288. {
  7289. if (nextChar!='{' && nextChar!='[') //already positioned at start
  7290. {
  7291. if (!checkReadNext())
  7292. return false;
  7293. if (checkBOM())
  7294. if (!checkReadNext())
  7295. return false;
  7296. if (!checkSkipWS())
  7297. return false;
  7298. }
  7299. if (noRoot)
  7300. rootItem();
  7301. else
  7302. {
  7303. switch (nextChar)
  7304. {
  7305. case '{':
  7306. state=objAttributes;
  7307. readNext();
  7308. beginNode("__object__", curOffset, elementTypeObject);
  7309. break;
  7310. case '[':
  7311. state=valueStart;
  7312. readNext();
  7313. beginNode("__array__", curOffset, elementTypeArray);
  7314. break;
  7315. default:
  7316. expecting("{ or [");
  7317. break;
  7318. }
  7319. }
  7320. break;
  7321. }
  7322. case nameStart:
  7323. namedItem();
  7324. break;
  7325. case objAttributes:
  7326. {
  7327. if ('}'==nextChar)
  7328. {
  7329. state=itemEnd;
  7330. iEvent->beginNodeContent(stateInfo->wnsTag);
  7331. break;
  7332. }
  7333. checkDelimiter(", or }");
  7334. if (nextChar != '\"')
  7335. expecting("\"");
  7336. readName(tag.clear());
  7337. if (tag.charAt(0)=='@')
  7338. newNamedAttribute();
  7339. else
  7340. {
  7341. preReadItemName = true;
  7342. state=itemContent;
  7343. stateInfo->childCount=0;
  7344. iEvent->beginNodeContent(stateInfo->wnsTag);
  7345. }
  7346. break;
  7347. }
  7348. case valueStart:
  7349. state=itemContent;
  7350. iEvent->beginNodeContent(stateInfo->wnsTag);
  7351. break;
  7352. case itemContent:
  7353. {
  7354. switch (stateInfo->type)
  7355. {
  7356. case elementTypeBool:
  7357. case elementTypeString:
  7358. case elementTypeInteger:
  7359. case elementTypeReal:
  7360. case elementTypeNull:
  7361. return endNode(curOffset);
  7362. break;
  7363. case elementTypeArray:
  7364. if (']'!=nextChar)
  7365. checkDelimiter(", or ]");
  7366. return arrayItem(curOffset);
  7367. case elementTypeObject:
  7368. if ('}'!=nextChar)
  7369. {
  7370. checkDelimiter(", or }");
  7371. namedItem();
  7372. }
  7373. else
  7374. {
  7375. if (stack.ordinality()>1)
  7376. readNext();
  7377. return endNode(curOffset);
  7378. }
  7379. break;
  7380. }
  7381. break;
  7382. }
  7383. case itemEnd:
  7384. {
  7385. if (!stack.length())
  7386. {
  7387. if (!noRoot || !rootNext())
  7388. return false;
  7389. readNext();
  7390. skipWS();
  7391. rootItem();
  7392. }
  7393. else
  7394. {
  7395. readNext();
  7396. state = itemContent;
  7397. return endNode(curOffset);
  7398. }
  7399. break;
  7400. }
  7401. }
  7402. return true;
  7403. }
  7404. };
  7405. IPTreeReader *createJSONStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize)
  7406. {
  7407. class CJSONStreamReader : public CJSONReader<CInstStreamReader>
  7408. {
  7409. public:
  7410. CJSONStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize=0) : CJSONReader<CInstStreamReader>(stream, iEvent, readerOptions, bufSize) { }
  7411. };
  7412. return new CJSONStreamReader(stream, iEvent, readerOptions, bufSize);
  7413. }
  7414. IPTreeReader *createJSONStringReader(const char *json, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  7415. {
  7416. class CJSONStringReader : public CJSONReader<CInstStringReader>
  7417. {
  7418. public:
  7419. CJSONStringReader(const void *json, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions) : CJSONReader<CInstStringReader>(json, iEvent, readerOptions) { }
  7420. };
  7421. if (NULL == json)
  7422. throw createPTreeReadException(PTreeRead_syntax, "Null string passed to createJSONStringReader", NULL, 0, 0);
  7423. return new CJSONStringReader(json, iEvent, readerOptions);
  7424. }
  7425. IPTreeReader *createJSONBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  7426. {
  7427. class CJSONBufferReader : public CJSONReader<CInstBufferReader>
  7428. {
  7429. public:
  7430. CJSONBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions) : CJSONReader<CInstBufferReader>(buf, bufLength, iEvent, readerOptions) { }
  7431. };
  7432. return new CJSONBufferReader(buf, bufLength, iEvent, readerOptions);
  7433. }
  7434. IPullPTreeReader *createPullJSONStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize)
  7435. {
  7436. class CJSONStreamReader : public CPullJSONReader<CInstStreamReader>
  7437. {
  7438. public:
  7439. CJSONStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize=0) : CPullJSONReader<CInstStreamReader>(stream, iEvent, readerOptions, bufSize) { }
  7440. };
  7441. return new CJSONStreamReader(stream, iEvent, readerOptions, bufSize);
  7442. }
  7443. IPullPTreeReader *createPullJSONStringReader(const char *json, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  7444. {
  7445. class CJSONStringReader : public CPullJSONReader<CInstStringReader>
  7446. {
  7447. public:
  7448. CJSONStringReader(const void *json, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions) : CPullJSONReader<CInstStringReader>(json, iEvent, readerOptions) { }
  7449. };
  7450. return new CJSONStringReader(json, iEvent, readerOptions);
  7451. }
  7452. IPullPTreeReader *createPullJSONBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  7453. {
  7454. class CJSONBufferReader : public CPullJSONReader<CInstBufferReader>
  7455. {
  7456. public:
  7457. CJSONBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions) : CPullJSONReader<CInstBufferReader>(buf, bufLength, iEvent, readerOptions) { }
  7458. };
  7459. return new CJSONBufferReader(buf, bufLength, iEvent, readerOptions);
  7460. }
  7461. IPropertyTree *createPTreeFromJSONString(const char *json, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  7462. {
  7463. Owned<IPTreeMaker> _iMaker;
  7464. if (!iMaker)
  7465. {
  7466. iMaker = createDefaultPTreeMaker(flags, readFlags);
  7467. _iMaker.setown(iMaker);
  7468. }
  7469. Owned<IPTreeReader> reader = createJSONStringReader(json, *iMaker, readFlags);
  7470. reader->load();
  7471. return LINK(iMaker->queryRoot());
  7472. }
  7473. IPropertyTree *createPTreeFromJSONString(unsigned len, const char *json, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  7474. {
  7475. Owned<IPTreeMaker> _iMaker;
  7476. if (!iMaker)
  7477. {
  7478. iMaker = createDefaultPTreeMaker(flags, readFlags);
  7479. _iMaker.setown(iMaker);
  7480. }
  7481. Owned<IPTreeReader> reader = createJSONBufferReader(json, len, *iMaker, readFlags);
  7482. reader->load();
  7483. return LINK(iMaker->queryRoot());
  7484. }
  7485. static const char * nextHttpParameterTag(StringBuffer &tag, const char *path)
  7486. {
  7487. while (*path=='.')
  7488. path++;
  7489. const char *finger = strchr(path, '.');
  7490. if (finger)
  7491. {
  7492. tag.clear().append(finger - path, path);
  7493. finger++;
  7494. }
  7495. else
  7496. tag.set(path);
  7497. return finger;
  7498. }
  7499. static void ensureHttpParameter(IPropertyTree *pt, StringBuffer &tag, const char *path, const char *value, const char *fullpath)
  7500. {
  7501. if (!tag.length())
  7502. return;
  7503. unsigned idx = 1;
  7504. if (path && isdigit(*path))
  7505. {
  7506. StringBuffer pos;
  7507. path = nextHttpParameterTag(pos, path);
  7508. idx = (unsigned) atoi(pos.str())+1;
  7509. }
  7510. if ('@'==*tag)
  7511. {
  7512. if (path && *path)
  7513. throw MakeStringException(-1, "'@' not allowed in parent node of parameter path: %s", fullpath);
  7514. pt->setProp(tag, value);
  7515. return;
  7516. }
  7517. if (tag.charAt(tag.length()-1)=='$')
  7518. {
  7519. if (path && *path)
  7520. throw MakeStringException(-1, "'$' not allowed in parent node of parameter path: %s", fullpath);
  7521. tag.setLength(tag.length()-1);
  7522. StringArray values;
  7523. values.appendList(value, "\r");
  7524. ForEachItemIn(pos, values)
  7525. {
  7526. const char *itemValue = values.item(pos);
  7527. while (*itemValue=='\n')
  7528. itemValue++;
  7529. pt->addProp(tag, itemValue);
  7530. }
  7531. return;
  7532. }
  7533. unsigned count = pt->getCount(tag);
  7534. while (count++ < idx)
  7535. pt->addPropTree(tag, createPTree(tag));
  7536. StringBuffer xpath(tag);
  7537. xpath.append('[').append(idx).append(']');
  7538. pt = pt->queryPropTree(xpath);
  7539. if (!path || !*path)
  7540. {
  7541. pt->setProp(NULL, value);
  7542. return;
  7543. }
  7544. StringBuffer nextTag;
  7545. path = nextHttpParameterTag(nextTag, path);
  7546. ensureHttpParameter(pt, nextTag, path, value, fullpath);
  7547. }
  7548. static void ensureHttpParameter(IPropertyTree *pt, const char *path, const char *value)
  7549. {
  7550. const char *fullpath = path;
  7551. StringBuffer tag;
  7552. path = nextHttpParameterTag(tag, path);
  7553. ensureHttpParameter(pt, tag, path, value, fullpath);
  7554. }
  7555. bool checkParseUrlPathNodeValue(const char *s, StringBuffer &name, StringAttr &value)
  7556. {
  7557. s = skipWhitespace(s);
  7558. const char *pn = strchr(s, '(');
  7559. if (pn) //strict format param('value') so we can extend later
  7560. {
  7561. const char *vp = pn + 1;
  7562. if (*vp!='\'')
  7563. return false;
  7564. const char *end =strchr(++vp, '\'');
  7565. if (!end || *(end+1)!=')')
  7566. return false;
  7567. if (!validateXMLTag(name.append(pn-s, s).trim()))
  7568. return false;
  7569. value.set(vp, end-vp);
  7570. }
  7571. else
  7572. {
  7573. if (!validateXMLTag(name.append(s).trim()))
  7574. return false;
  7575. }
  7576. return true;
  7577. }
  7578. IPropertyTree *createPTreeFromHttpPath(const char *nameWithAttrs, IPropertyTree *content, bool nestedRoot, ipt_flags flags)
  7579. {
  7580. StringArray nameAttrList;
  7581. nameAttrList.appendList(nameWithAttrs, "/");
  7582. if (!nameAttrList.ordinality())
  7583. return NULL;
  7584. Owned<IPropertyTree> pt = createPTree(nameAttrList.item(0), flags);
  7585. for (aindex_t pos=1; nameAttrList.isItem(pos); pos++)
  7586. {
  7587. StringBuffer name;
  7588. StringAttr value;
  7589. if (!checkParseUrlPathNodeValue(nameAttrList.item(pos), name, value))
  7590. throw MakeStringException(-1, "Invalid URL parameter format %s", nameAttrList.item(pos));
  7591. StringBuffer xpath("@");
  7592. xpath.append(name.str());
  7593. if (!value.get())
  7594. pt->setPropBool(xpath, true);
  7595. else
  7596. pt->setProp(xpath, value);
  7597. }
  7598. IPropertyTree *parent = pt;
  7599. const char *input = pt->queryProp("@input");
  7600. if (input)
  7601. {
  7602. StringArray inputNodes;
  7603. inputNodes.appendList(input, ".");
  7604. ForEachItemIn(in, inputNodes)
  7605. {
  7606. const char *tag = inputNodes.item(in);
  7607. if (!validateXMLTag(tag))
  7608. throw MakeStringException(-1, "Invalid REST query input specifier %s", input);
  7609. parent = parent->addPropTree(tag, createPTree(tag, flags));
  7610. }
  7611. }
  7612. if (streq("__array__", content->queryName()))
  7613. {
  7614. Owned<IAttributeIterator> aiter = content->getAttributes();
  7615. ForEach (*aiter)
  7616. parent->addProp(aiter->queryName(), aiter->queryValue());
  7617. Owned<IPropertyTreeIterator> iter = content->getElements("__item__");
  7618. ForEach (*iter)
  7619. {
  7620. IPropertyTree &e = iter->query();
  7621. e.renameProp("/", "Row");
  7622. parent->addPropTree("Row", LINK(&e));
  7623. }
  7624. }
  7625. else
  7626. mergePTree(parent, content);
  7627. if (nestedRoot)
  7628. {
  7629. Owned<IPropertyTree> root = createPTree(flags);
  7630. root->setPropTree(nameAttrList.item(0), pt.getClear());
  7631. return root.getClear();
  7632. }
  7633. return pt.getClear();
  7634. }
  7635. //URL node nameWithAttrs is of the form: "TagName/attr1('abc')/attr2/attr3('xyz')"
  7636. IPropertyTree *createPTreeFromHttpParameters(const char *nameWithAttrs, IProperties *parameters, bool skipLeadingDotParameters, bool nestedRoot, ipt_flags flags)
  7637. {
  7638. Owned<IPropertyTree> content = createPTree("content", flags);
  7639. Owned<IPropertyIterator> iter = parameters->getIterator();
  7640. ForEach(*iter)
  7641. {
  7642. StringBuffer key(iter->getPropKey());
  7643. if (!key.length() || key.charAt(key.length()-1)=='!')
  7644. continue;
  7645. if (skipLeadingDotParameters && key.charAt(0)=='.')
  7646. continue;
  7647. const char *value = parameters->queryProp(key);
  7648. if (!value || !*value)
  7649. continue;
  7650. ensureHttpParameter(content, key, value);
  7651. }
  7652. return createPTreeFromHttpPath(nameWithAttrs, content.getClear(), nestedRoot, flags);
  7653. }
  7654. IPropertyTree *createPTreeFromJSONFile(const char *filename, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  7655. {
  7656. Owned<IFile> in = createIFile(filename);
  7657. if (!in->exists())
  7658. return nullptr;
  7659. StringBuffer contents;
  7660. try
  7661. {
  7662. contents.loadFile(in);
  7663. }
  7664. catch (IException * e)
  7665. {
  7666. EXCLOG(e);
  7667. e->Release();
  7668. return nullptr;
  7669. }
  7670. return createPTreeFromJSONString(contents.length(), contents.str(), flags, readFlags, iMaker);
  7671. }
  7672. //---------------------------------------------------------------------------------------------------------------------
  7673. static constexpr const char * currentVersion = "1.0";
  7674. //---------------------------------------------------------------------------------------------------------------------
  7675. /*
  7676. * Use source to overwrite any changes in target
  7677. * Attributes are replaced
  7678. * Singleton elements are replaced.
  7679. * Entire arrays of scalar elements are replaced.
  7680. * Entire arrays of elements with no name attribute are replaced.
  7681. * Elements with a name attribute are matched by name. If there is a match it is merged. If there is no match it is added.
  7682. */
  7683. static bool checkInSequence(IPropertyTree & child, StringAttr &seqname, bool &first, bool &endprior)
  7684. {
  7685. first = false;
  7686. endprior = false;
  7687. if (seqname.length() && streq(seqname, child.queryName()))
  7688. return true;
  7689. endprior = !seqname.isEmpty();
  7690. if (child.isArray(nullptr))
  7691. {
  7692. first=true;
  7693. seqname.set(child.queryName());
  7694. return true;
  7695. }
  7696. seqname.clear();
  7697. return false;
  7698. }
  7699. inline bool isScalarItem(IPropertyTree &child)
  7700. {
  7701. if (child.hasChildren())
  7702. return false;
  7703. return child.getAttributeCount()==0;
  7704. }
  7705. static IPropertyTree *ensureMergeConfigTarget(IPropertyTree &target, const char *tag, const char *nameAttribute, const char *name, bool sequence)
  7706. {
  7707. StringBuffer tempPath;
  7708. const char * path = (sequence) ? nullptr : tag;
  7709. if (name && nameAttribute && *nameAttribute)
  7710. {
  7711. tempPath.append(tag).append("[").append(nameAttribute).append("=\'").append(name).append("']");
  7712. path = tempPath;
  7713. }
  7714. IPropertyTree * match = (path) ? target.queryPropTree(path) : nullptr;
  7715. if (!match)
  7716. {
  7717. if (sequence)
  7718. match = target.addPropTreeArrayItem(tag, createPTree(tag));
  7719. else
  7720. match = target.addPropTree(tag);
  7721. }
  7722. return match;
  7723. }
  7724. void mergeConfiguration(IPropertyTree & target, IPropertyTree & source, const char *altNameAttribute)
  7725. {
  7726. Owned<IAttributeIterator> aiter = source.getAttributes();
  7727. ForEach(*aiter)
  7728. target.addProp(aiter->queryName(), aiter->queryValue());
  7729. StringAttr seqname;
  7730. Owned<IPropertyTreeIterator> iter = source.getElements("*");
  7731. ForEach(*iter)
  7732. {
  7733. IPropertyTree & child = iter->query();
  7734. const char * tag = child.queryName();
  7735. const char * name = child.queryProp("@name");
  7736. bool altname = false;
  7737. //Legacy support for old component configuration files that have repeated elements with no name tag but another unique id
  7738. if (!name && altNameAttribute && *altNameAttribute)
  7739. {
  7740. name = child.queryProp(altNameAttribute);
  7741. altname = name!=nullptr;
  7742. }
  7743. bool first = false;
  7744. bool endprior = false;
  7745. bool sequence = checkInSequence(child, seqname, first, endprior);
  7746. if (first && (!name || isScalarItem(child))) //arrays of unamed objects or scalars are replaced
  7747. target.removeProp(tag);
  7748. IPropertyTree * match = ensureMergeConfigTarget(target, tag, altname ? altNameAttribute : "@name", name, sequence);
  7749. mergeConfiguration(*match, child, altNameAttribute);
  7750. }
  7751. const char * sourceValue = source.queryProp("");
  7752. if (sourceValue)
  7753. target.setProp("", sourceValue);
  7754. }
  7755. /*
  7756. * Load a json/yaml configuration file.
  7757. * If there is an extends tag in the root of the file then this file is applied as a delta to the base file
  7758. * the configuration is the contents of the tag within the file that matches the component tag.
  7759. */
  7760. static IPropertyTree * loadConfiguration(const char * filename, const char * componentTag, bool required, const char *altNameAttribute)
  7761. {
  7762. if (!checkFileExists(filename))
  7763. throw makeStringExceptionV(99, "Configuration file %s not found", filename);
  7764. const char * ext = pathExtension(filename);
  7765. Owned<IPropertyTree> configTree;
  7766. if (!ext || strieq(ext, ".yaml"))
  7767. {
  7768. try
  7769. {
  7770. configTree.setown(createPTreeFromYAMLFile(filename, 0, ptr_ignoreWhiteSpace, nullptr));
  7771. }
  7772. catch (IException *E)
  7773. {
  7774. StringBuffer msg;
  7775. E->errorMessage(msg);
  7776. ::Release(E);
  7777. throw makeStringExceptionV(99, "Error loading configuration file %s (invalid yaml): %s", filename, msg.str());
  7778. }
  7779. }
  7780. else
  7781. throw makeStringExceptionV(99, "Unrecognised file extension %s", ext);
  7782. if (!configTree)
  7783. throw makeStringExceptionV(99, "Error loading configuration file %s", filename);
  7784. IPropertyTree * config = configTree->queryPropTree(componentTag);
  7785. if (!config)
  7786. {
  7787. if (required)
  7788. throw makeStringExceptionV(99, "Section %s is missing from file %s", componentTag, filename);
  7789. return nullptr;
  7790. }
  7791. const char * base = configTree->queryProp("@extends");
  7792. if (!base)
  7793. return LINK(config);
  7794. StringBuffer baseFilename;
  7795. splitFilename(filename, &baseFilename, &baseFilename, nullptr, nullptr, false);
  7796. addNonEmptyPathSepChar(baseFilename);
  7797. baseFilename.append(base);
  7798. Owned<IPropertyTree> baseTree = loadConfiguration(baseFilename, componentTag, required, altNameAttribute);
  7799. mergeConfiguration(*baseTree, *config, altNameAttribute);
  7800. return LINK(baseTree);
  7801. }
  7802. static constexpr const char * envPrefix = "HPCC_CONFIG_";
  7803. static void applyEnvironmentConfig(IPropertyTree & target, const char * cptPrefix, const char * value)
  7804. {
  7805. const char * name = value;
  7806. if (!startsWith(name, envPrefix))
  7807. return;
  7808. name += strlen(envPrefix);
  7809. if (cptPrefix)
  7810. {
  7811. if (!startsWith(name, cptPrefix))
  7812. return;
  7813. name += strlen(cptPrefix);
  7814. if (*name++ != '_')
  7815. return;
  7816. }
  7817. StringBuffer propName;
  7818. if (startsWith(name, "PROP_"))
  7819. {
  7820. propName.append("@");
  7821. name += 5;
  7822. }
  7823. const char * eq = strchr(value, '=');
  7824. if (eq)
  7825. {
  7826. propName.append(eq - name, name);
  7827. target.setProp(propName, eq + 1);
  7828. }
  7829. else
  7830. {
  7831. propName.append(name);
  7832. target.setProp(propName, nullptr);
  7833. }
  7834. }
  7835. IPropertyTree * createPTreeFromYAML(const char * yaml)
  7836. {
  7837. if (*yaml == '{')
  7838. return createPTreeFromJSONString(yaml, 0, ptr_ignoreWhiteSpace, nullptr);
  7839. return createPTreeFromYAMLString(yaml, 0, ptr_ignoreWhiteSpace, nullptr);
  7840. }
  7841. static const char * extractOption(const char * option, const char * cur)
  7842. {
  7843. if (startsWith(cur, option))
  7844. {
  7845. cur += strlen(option);
  7846. if (*cur == '=')
  7847. return cur + 1;
  7848. if (*cur)
  7849. return nullptr;
  7850. return "1";
  7851. }
  7852. return nullptr;
  7853. }
  7854. static void applyCommandLineOption(IPropertyTree * config, const char * option, const char * value)
  7855. {
  7856. //Ignore -- with no following option.
  7857. if (isEmptyString(option))
  7858. return;
  7859. const char *tail;
  7860. while ((tail = strchr(option, '.')) != nullptr)
  7861. {
  7862. StringAttr elemName(option, tail-option);
  7863. if (!config->hasProp(elemName))
  7864. config = config->addPropTree(elemName);
  7865. else
  7866. {
  7867. config = config->queryPropTree(elemName);
  7868. if (!config)
  7869. throw makeStringExceptionV(99, "Cannot overriding scalar configuration element %s with structure", elemName.get());
  7870. }
  7871. option = tail+1;
  7872. }
  7873. if (!validateXMLTag(option))
  7874. throw makeStringExceptionV(99, "Invalid option name '%s'", option);
  7875. StringBuffer path;
  7876. path.append('@').append(option);
  7877. config->setProp(path, value);
  7878. }
  7879. static void applyCommandLineOption(IPropertyTree * config, const char * option, std::initializer_list<const char *> ignoreOptions)
  7880. {
  7881. const char * eq = strchr(option, '=');
  7882. StringBuffer name;
  7883. const char *val = nullptr;
  7884. if (eq)
  7885. {
  7886. name.append(eq - option, option);
  7887. option = name;
  7888. val = eq + 1;
  7889. }
  7890. else
  7891. {
  7892. //MORE: Support --x- and --x+?
  7893. val = "1";
  7894. }
  7895. if (stdContains(ignoreOptions, option))
  7896. return;
  7897. applyCommandLineOption(config, option, val);
  7898. }
  7899. static Owned<IPropertyTree> componentConfiguration;
  7900. static Owned<IPropertyTree> globalConfiguration;
  7901. MODULE_INIT(INIT_PRIORITY_STANDARD)
  7902. {
  7903. return true;
  7904. }
  7905. MODULE_EXIT()
  7906. {
  7907. componentConfiguration.clear();
  7908. globalConfiguration.clear();
  7909. }
  7910. IPropertyTree & queryComponentConfig()
  7911. {
  7912. if (!componentConfiguration)
  7913. throw makeStringException(99, "Configuration file has not yet been processed");
  7914. return *componentConfiguration;
  7915. }
  7916. IPropertyTree & queryGlobalConfig()
  7917. {
  7918. if (!globalConfiguration)
  7919. throw makeStringException(99, "Configuration file has not yet been processed");
  7920. return *globalConfiguration;
  7921. }
  7922. jlib_decl IPropertyTree * loadArgsIntoConfiguration(IPropertyTree *config, const char * * argv, std::initializer_list<const char *> ignoreOptions)
  7923. {
  7924. for (const char * * pArg = argv; *pArg; pArg++)
  7925. {
  7926. const char * cur = *pArg;
  7927. if (startsWith(cur, "--"))
  7928. applyCommandLineOption(config, cur + 2, ignoreOptions);
  7929. }
  7930. return config;
  7931. }
  7932. #ifdef _DEBUG
  7933. static void holdLoop()
  7934. {
  7935. DBGLOG("Component paused for debugging purposes, attach and set held=false to release");
  7936. bool held = true;
  7937. while (held)
  7938. Sleep(5);
  7939. }
  7940. #endif
  7941. jlib_decl IPropertyTree * loadConfiguration(IPropertyTree *componentDefault, const char * * argv, const char * componentTag, const char * envPrefix, const char * legacyFilename, IPropertyTree * (mapper)(IPropertyTree *), const char *altNameAttribute)
  7942. {
  7943. if (componentConfiguration)
  7944. throw makeStringExceptionV(99, "Configuration for component %s has already been initialised", componentTag);
  7945. Linked<IPropertyTree> config(componentDefault);
  7946. const char * optConfig = nullptr;
  7947. bool outputConfig = false;
  7948. #ifdef _DEBUG
  7949. bool held = false;
  7950. #endif
  7951. for (const char * * pArg = argv; *pArg; pArg++)
  7952. {
  7953. const char * cur = *pArg;
  7954. const char * matchConfig = extractOption("--config", cur);
  7955. if (matchConfig)
  7956. optConfig = matchConfig;
  7957. else if (strsame(cur, "--help"))
  7958. {
  7959. #if 0
  7960. //Better not to include this until it has been implemented, since it breaks eclcc
  7961. //MORE: displayHelp(config);
  7962. printf("%s <options>\n", argv[0]);
  7963. exit(0);
  7964. #endif
  7965. }
  7966. else if (strsame(cur, "--init"))
  7967. {
  7968. StringBuffer yamlText;
  7969. toYAML(componentDefault, yamlText, 0, YAML_SortTags);
  7970. printf("%s\n", yamlText.str());
  7971. exit(0);
  7972. }
  7973. else if (strsame(cur, "--outputconfig"))
  7974. {
  7975. outputConfig = true;
  7976. }
  7977. #ifdef _DEBUG
  7978. else
  7979. {
  7980. const char *matchHold = extractOption("--hold", cur);
  7981. if (matchHold)
  7982. {
  7983. if (strToBool(matchHold))
  7984. {
  7985. held = true;
  7986. holdLoop();
  7987. }
  7988. }
  7989. }
  7990. #endif
  7991. }
  7992. Owned<IPropertyTree> delta;
  7993. if (optConfig)
  7994. {
  7995. if (streq(optConfig, "1"))
  7996. throw makeStringExceptionV(99, "Name of configuration file omitted (use --config=<filename>)");
  7997. //--config= with no filename can be used to ignore the legacy configuration file
  7998. if (!isEmptyString(optConfig))
  7999. {
  8000. StringBuffer fullpath;
  8001. if (!isAbsolutePath(optConfig))
  8002. {
  8003. appendCurrentDirectory(fullpath, false);
  8004. addNonEmptyPathSepChar(fullpath);
  8005. }
  8006. fullpath.append(optConfig);
  8007. delta.setown(loadConfiguration(fullpath, componentTag, true, altNameAttribute));
  8008. globalConfiguration.setown(loadConfiguration(fullpath, "global", false, altNameAttribute));
  8009. }
  8010. }
  8011. else
  8012. {
  8013. if (legacyFilename && checkFileExists(legacyFilename))
  8014. delta.setown(createPTreeFromXMLFile(legacyFilename, ipt_caseInsensitive));
  8015. if (delta && mapper)
  8016. delta.setown(mapper(delta));
  8017. }
  8018. if (delta)
  8019. mergeConfiguration(*config, *delta, altNameAttribute);
  8020. const char * * environment = const_cast<const char * *>(getSystemEnv());
  8021. for (const char * * cur = environment; *cur; cur++)
  8022. {
  8023. applyEnvironmentConfig(*config, envPrefix, *cur);
  8024. }
  8025. if (outputConfig)
  8026. {
  8027. loadArgsIntoConfiguration(config, argv, { "config", "outputconfig" });
  8028. Owned<IPropertyTree> recreated = createPTree();
  8029. recreated->setProp("@version", currentVersion);
  8030. recreated->addPropTree(componentTag, LINK(config));
  8031. if (globalConfiguration)
  8032. recreated->addPropTree("global", globalConfiguration.getLink());
  8033. StringBuffer yamlText;
  8034. toYAML(recreated, yamlText, 0, YAML_SortTags);
  8035. printf("%s\n", yamlText.str());
  8036. exit(0);
  8037. }
  8038. else
  8039. loadArgsIntoConfiguration(config, argv);
  8040. //For legacy (and other weird cases) ensure there is a global section
  8041. if (!globalConfiguration)
  8042. globalConfiguration.setown(createPTree("global"));
  8043. #ifdef _DEBUG
  8044. // NB: don't re-hold, if CLI --hold already held.
  8045. if (!held && config->getPropBool("@hold"))
  8046. holdLoop();
  8047. #endif
  8048. unsigned ptreeMappingThreshold = globalConfiguration->getPropInt("@ptreeMappingThreshold", defaultSiblingMapThreshold);
  8049. setPTreeMappingThreshold(ptreeMappingThreshold);
  8050. componentConfiguration.set(config);
  8051. return config.getClear();
  8052. }
  8053. jlib_decl IPropertyTree * loadConfiguration(const char * defaultYaml, const char * * argv, const char * componentTag, const char * envPrefix, const char * legacyFilename, IPropertyTree * (mapper)(IPropertyTree *), const char *altNameAttribute)
  8054. {
  8055. if (componentConfiguration)
  8056. throw makeStringExceptionV(99, "Configuration for component %s has already been initialised", componentTag);
  8057. Owned<IPropertyTree> componentDefault;
  8058. if (defaultYaml)
  8059. {
  8060. Owned<IPropertyTree> defaultConfig = createPTreeFromYAML(defaultYaml);
  8061. componentDefault.set(defaultConfig->queryPropTree(componentTag));
  8062. if (!componentDefault)
  8063. throw makeStringExceptionV(99, "Default configuration does not contain the tag %s", componentTag);
  8064. }
  8065. else
  8066. componentDefault.setown(createPTree(componentTag));
  8067. return loadConfiguration(componentDefault, argv, componentTag, envPrefix, legacyFilename, mapper, altNameAttribute);
  8068. }
  8069. class CYAMLBufferReader : public CInterfaceOf<IPTreeReader>
  8070. {
  8071. protected:
  8072. Linked<IPTreeNotifyEvent> iEvent;
  8073. yaml_parser_t parser;
  8074. PTreeReaderOptions readerOptions = ptr_none;
  8075. bool noRoot = false;
  8076. public:
  8077. CYAMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
  8078. iEvent(&_iEvent), readerOptions(_readerOptions)
  8079. {
  8080. if (!yaml_parser_initialize(&parser))
  8081. throw makeStringException(99, "Filed to initialize libyaml parser");
  8082. yaml_parser_set_input_string(&parser, (const unsigned char *)buf, bufLength);
  8083. noRoot = 0 != ((unsigned)readerOptions & (unsigned)ptr_noRoot);
  8084. }
  8085. ~CYAMLBufferReader()
  8086. {
  8087. yaml_parser_delete(&parser);
  8088. }
  8089. yaml_event_type_t nextEvent(yaml_event_t &event, yaml_event_type_t final=YAML_NO_EVENT, yaml_event_type_t expected=YAML_NO_EVENT, const char *error="")
  8090. {
  8091. if (!yaml_parser_parse(&parser, &event))
  8092. throw makeStringExceptionV(99, "libyaml parser error %s", parser.problem);
  8093. if (event.type!=final && expected!=YAML_NO_EVENT && event.type!=expected)
  8094. throw makeStringExceptionV(99, "libyaml parser %s", error);
  8095. return event.type;
  8096. }
  8097. virtual void loadSequence(const char *tagname)
  8098. {
  8099. if (!tagname || !*tagname) //if unmapped (unnamed) sequences are possible have to decide how to name them in the ptree, later
  8100. throw makeStringException(99, "libyaml parser expected sequence name");
  8101. yaml_event_t event;
  8102. yaml_event_type_t eventType = YAML_NO_EVENT;
  8103. while (eventType!=YAML_SEQUENCE_END_EVENT)
  8104. {
  8105. eventType = nextEvent(event);
  8106. switch (eventType)
  8107. {
  8108. case YAML_MAPPING_START_EVENT: //child map
  8109. loadMap(tagname, true);
  8110. break;
  8111. case YAML_SEQUENCE_START_EVENT:
  8112. //todo
  8113. break;
  8114. case YAML_SCALAR_EVENT:
  8115. iEvent->beginNode(tagname, true, parser.offset);
  8116. iEvent->endNode(tagname, event.data.scalar.length, (const void *)event.data.scalar.value, false, parser.offset);
  8117. break;
  8118. case YAML_ALIAS_EVENT: //reference to an anchor, ignore for now
  8119. iEvent->beginNode(tagname, true, parser.offset);
  8120. iEvent->endNode(tagname, 0, nullptr, false, parser.offset);
  8121. break;
  8122. case YAML_SEQUENCE_END_EVENT: //done
  8123. break;
  8124. case YAML_NO_EVENT:
  8125. case YAML_MAPPING_END_EVENT:
  8126. case YAML_STREAM_START_EVENT:
  8127. case YAML_STREAM_END_EVENT:
  8128. case YAML_DOCUMENT_START_EVENT:
  8129. case YAML_DOCUMENT_END_EVENT:
  8130. default:
  8131. //shouldn't be here
  8132. break;
  8133. }
  8134. yaml_event_delete(&event);
  8135. }
  8136. }
  8137. virtual void loadMap(const char *tagname, bool sequence)
  8138. {
  8139. bool binaryContent = false;
  8140. StringBuffer content;
  8141. if (tagname && *tagname)
  8142. iEvent->beginNode(tagname, sequence, parser.offset);
  8143. yaml_event_t event;
  8144. yaml_event_type_t eventType = YAML_NO_EVENT;
  8145. while (eventType!=YAML_MAPPING_END_EVENT)
  8146. {
  8147. eventType = nextEvent(event, YAML_MAPPING_END_EVENT, YAML_SCALAR_EVENT, "expected map to start with scalar name");
  8148. if (eventType==YAML_MAPPING_END_EVENT)
  8149. {
  8150. yaml_event_delete(&event);
  8151. continue;
  8152. }
  8153. StringBuffer attname('@');
  8154. attname.append(event.data.scalar.length, (const char *)event.data.scalar.value);
  8155. const char *elname = attname.str()+1;
  8156. yaml_event_delete(&event);
  8157. eventType = nextEvent(event);
  8158. switch (eventType)
  8159. {
  8160. case YAML_MAPPING_START_EVENT: //child map
  8161. loadMap(elname, false);
  8162. break;
  8163. case YAML_SEQUENCE_START_EVENT:
  8164. loadSequence(elname);
  8165. break;
  8166. case YAML_SCALAR_EVENT:
  8167. {
  8168. //!el or !element will be our local tag (custom schema type) for an element
  8169. //ptree toYAML should set this for element scalars, and parent text content
  8170. const char *tag = (const char *)event.data.scalar.tag;
  8171. if (tag && (streq(tag, "!binary") || streq(tag, "!!binary")))
  8172. {
  8173. if (streq(elname, "^")) //text content of parent node
  8174. {
  8175. binaryContent = true;
  8176. JBASE64_Decode((const char *) event.data.scalar.value, content.clear());
  8177. }
  8178. else
  8179. {
  8180. StringBuffer decoded;
  8181. JBASE64_Decode((const char *) event.data.scalar.value, decoded);
  8182. iEvent->beginNode(elname, false, parser.offset);
  8183. iEvent->endNode(elname, decoded.length(), (const void *) decoded.str(), true, parser.offset);
  8184. }
  8185. }
  8186. else if (streq(elname, "^")) //text content of parent node
  8187. {
  8188. content.set((const char *) event.data.scalar.value);
  8189. }
  8190. else if (tag && (streq(tag, "!el") || streq(tag, "!element")))
  8191. {
  8192. iEvent->beginNode(elname, false, parser.offset);
  8193. iEvent->endNode(elname, event.data.scalar.length, (const void *) event.data.scalar.value, false, parser.offset);
  8194. }
  8195. else //by default all named scalars are ptree attributes
  8196. {
  8197. iEvent->newAttribute(attname, (const char *)event.data.scalar.value);
  8198. }
  8199. break;
  8200. }
  8201. case YAML_ALIAS_EVENT: //reference to an anchor, ignore for now
  8202. iEvent->beginNode(elname, false, parser.offset);
  8203. iEvent->endNode(elname, 0, nullptr, false, parser.offset);
  8204. break;
  8205. case YAML_MAPPING_END_EVENT: //done
  8206. break;
  8207. case YAML_NO_EVENT:
  8208. case YAML_SEQUENCE_END_EVENT:
  8209. case YAML_STREAM_START_EVENT:
  8210. case YAML_STREAM_END_EVENT:
  8211. case YAML_DOCUMENT_START_EVENT:
  8212. case YAML_DOCUMENT_END_EVENT:
  8213. default:
  8214. //shouldn't be here
  8215. break;
  8216. }
  8217. yaml_event_delete(&event);
  8218. }
  8219. if (tagname && *tagname)
  8220. iEvent->endNode(tagname, content.length(), content, binaryContent, parser.offset);
  8221. }
  8222. virtual void load() override
  8223. {
  8224. yaml_event_t event;
  8225. yaml_event_type_t eventType = YAML_NO_EVENT;
  8226. bool doc = false;
  8227. bool content = false;
  8228. while (eventType!=YAML_STREAM_END_EVENT)
  8229. {
  8230. eventType = nextEvent(event);
  8231. switch (eventType)
  8232. {
  8233. case YAML_MAPPING_START_EVENT:
  8234. //root content, the start of all mappings, should be only one at the root
  8235. if (content)
  8236. throw makeStringException(99, "YAML: Currently only support one content section (map) per stream");
  8237. loadMap(noRoot ? nullptr : "__object__", false); //root map
  8238. content=true;
  8239. break;
  8240. case YAML_SEQUENCE_START_EVENT:
  8241. //root content, sequence (array), should be only one at the root and can't mix with mappings
  8242. if (content)
  8243. throw makeStringException(99, "YAML: Currently only support one content section (sequence) per stream");
  8244. if (!noRoot)
  8245. iEvent->beginNode("__array__", false, 0);
  8246. loadSequence("__item__");
  8247. if (!noRoot)
  8248. iEvent->endNode("__array__", 0, nullptr, false, parser.offset);
  8249. content=true;
  8250. break;
  8251. case YAML_STREAM_START_EVENT:
  8252. case YAML_STREAM_END_EVENT:
  8253. //don't think we need to do anything... unless we start saving hints
  8254. break;
  8255. case YAML_DOCUMENT_START_EVENT:
  8256. //should only support one? multiple documents would imply an extra level of nesting (future flag?)
  8257. if (doc)
  8258. throw makeStringException(99, "YAML: Currently only support one document per stream");
  8259. doc=true;
  8260. break;
  8261. case YAML_DOCUMENT_END_EVENT:
  8262. break;
  8263. case YAML_NO_EVENT:
  8264. case YAML_ALIAS_EVENT: //root alias?
  8265. case YAML_MAPPING_END_EVENT:
  8266. case YAML_SCALAR_EVENT: //root unmapped (unnamed) scalars?
  8267. case YAML_SEQUENCE_END_EVENT:
  8268. //shouldn't be here
  8269. break;
  8270. default:
  8271. break;
  8272. }
  8273. yaml_event_delete(&event);
  8274. }
  8275. }
  8276. virtual offset_t queryOffset() override
  8277. {
  8278. return parser.offset;
  8279. }
  8280. };
  8281. IPTreeReader *createYAMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
  8282. {
  8283. return new CYAMLBufferReader(buf, bufLength, iEvent, readerOptions);
  8284. }
  8285. IPropertyTree *createPTreeFromYAMLString(unsigned len, const char *yaml, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  8286. {
  8287. Owned<IPTreeMaker> _iMaker;
  8288. if (!iMaker)
  8289. {
  8290. iMaker = createDefaultPTreeMaker(flags, readFlags);
  8291. _iMaker.setown(iMaker);
  8292. }
  8293. Owned<IPTreeReader> reader = createYAMLBufferReader(yaml, len, *iMaker, readFlags);
  8294. reader->load();
  8295. return LINK(iMaker->queryRoot());
  8296. }
  8297. IPropertyTree *createPTreeFromYAMLString(const char *yaml, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  8298. {
  8299. return createPTreeFromYAMLString(strlen(yaml), yaml, flags, readFlags, iMaker);
  8300. }
  8301. IPropertyTree *createPTreeFromYAMLFile(const char *filename, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
  8302. {
  8303. Owned<IFile> in = createIFile(filename);
  8304. if (!in->exists())
  8305. return nullptr;
  8306. StringBuffer contents;
  8307. try
  8308. {
  8309. contents.loadFile(in);
  8310. }
  8311. catch (IException * e)
  8312. {
  8313. EXCLOG(e);
  8314. e->Release();
  8315. return nullptr;
  8316. }
  8317. return createPTreeFromYAMLString(contents.length(), contents, flags, readFlags, iMaker);
  8318. }
  8319. static int yaml_write_iiostream(void *data, unsigned char *buffer, size_t size)
  8320. {
  8321. IIOStream *out = (IIOStream *) data;
  8322. out->write(size, (void *)buffer);
  8323. out->flush();
  8324. return 0;
  8325. }
  8326. class YAMLEmitter
  8327. {
  8328. yaml_emitter_t emitter;
  8329. yaml_event_t event;
  8330. IIOStream &out;
  8331. public:
  8332. YAMLEmitter(IIOStream &ios, int indent) : out(ios)
  8333. {
  8334. if (!yaml_emitter_initialize(&emitter))
  8335. throw MakeStringException(0, "YAMLEmitter: failed to initialize");
  8336. yaml_emitter_set_output(&emitter, yaml_write_iiostream, &out);
  8337. yaml_emitter_set_canonical(&emitter, false);
  8338. yaml_emitter_set_unicode(&emitter, true);
  8339. yaml_emitter_set_indent(&emitter, indent);
  8340. beginStream();
  8341. beginDocument();
  8342. }
  8343. ~YAMLEmitter()
  8344. {
  8345. endDocument();
  8346. endStream();
  8347. yaml_emitter_delete(&emitter);
  8348. }
  8349. yaml_char_t *getTag(bool binary, bool element)
  8350. {
  8351. if (binary)
  8352. return (yaml_char_t *) "!binary";
  8353. if (element)
  8354. return (yaml_char_t *) "!el";
  8355. return nullptr;
  8356. }
  8357. void emit()
  8358. {
  8359. yaml_emitter_emit(&emitter, &event);
  8360. }
  8361. void checkInit(int success, const char *descr)
  8362. {
  8363. if (success==0)
  8364. throw MakeStringException(0, "YAMLEmitter: %s failed", descr);
  8365. }
  8366. void writeValue(const char *value, bool element, bool hidden, bool binary)
  8367. {
  8368. yaml_scalar_style_t style = binary ? YAML_LITERAL_SCALAR_STYLE : YAML_ANY_SCALAR_STYLE;
  8369. const yaml_char_t *tag = getTag(binary, element);
  8370. bool implicit = tag==nullptr;
  8371. StringBuffer s;
  8372. if (!value)
  8373. value = "null";
  8374. else if (hidden)
  8375. value = (binary) ? "KioqKg==" : s.appendN(strlen(value), '*').str(); //KioqKg== is base64 of ****
  8376. checkInit(yaml_scalar_event_initialize(&event, nullptr, tag, (yaml_char_t *) value, -1, implicit, implicit, style), "yaml_scalar_event_initialize");
  8377. emit();
  8378. }
  8379. void writeName(const char *name)
  8380. {
  8381. dbgassertex(name!=nullptr);
  8382. return writeValue(name, false, false,false);
  8383. }
  8384. void writeNamedValue(const char *name, const char *value, bool element, bool hidden)
  8385. {
  8386. writeName(name);
  8387. writeValue(value, element, hidden, false);
  8388. }
  8389. void writeAttribute(const char *name, const char *value, bool hidden)
  8390. {
  8391. writeNamedValue(name, value, false, hidden);
  8392. }
  8393. void beginMap()
  8394. {
  8395. checkInit(yaml_mapping_start_event_initialize(&event, nullptr, nullptr, 0, YAML_BLOCK_MAPPING_STYLE), "yaml_mapping_start_event_initialize");
  8396. emit();
  8397. }
  8398. void endMap()
  8399. {
  8400. checkInit(yaml_mapping_end_event_initialize(&event), "yaml_mapping_end_event_initialize");
  8401. emit();
  8402. }
  8403. void beginSequence(const char *name)
  8404. {
  8405. if (name)
  8406. writeName(name);
  8407. checkInit(yaml_sequence_start_event_initialize(&event, nullptr, nullptr, 0, YAML_ANY_SEQUENCE_STYLE), "yaml_sequence_start_event_initialize");
  8408. emit();
  8409. }
  8410. void endSequence()
  8411. {
  8412. checkInit(yaml_sequence_end_event_initialize(&event), "yaml_sequence_end_event_initialize");
  8413. emit();
  8414. }
  8415. void beginDocument()
  8416. {
  8417. checkInit(yaml_document_start_event_initialize(&event, nullptr, nullptr, nullptr, true), "yaml_document_start_event_initialize");
  8418. emit();
  8419. }
  8420. void endDocument()
  8421. {
  8422. checkInit(yaml_document_end_event_initialize(&event, true), "yaml_document_end_event_initialize");
  8423. emit();
  8424. }
  8425. void beginStream()
  8426. {
  8427. checkInit(yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING), "yaml_stream_start_event_initialize");
  8428. emit();
  8429. }
  8430. void endStream()
  8431. {
  8432. checkInit(yaml_stream_end_event_initialize(&event), "yaml_stream_end_event_initialize");
  8433. emit();
  8434. }
  8435. };
  8436. static void _toYAML(const IPropertyTree *tree, YAMLEmitter &yaml, byte flags, bool root=false, bool isArrayItem=false)
  8437. {
  8438. const char *name = tree->queryName();
  8439. if (!root && !isArrayItem)
  8440. {
  8441. if (!name || !*name)
  8442. name = "__unnamed__";
  8443. yaml.writeName(name);
  8444. }
  8445. Owned<IAttributeIterator> it = tree->getAttributes(true);
  8446. bool hasAttributes = it->first();
  8447. bool complex = (hasAttributes || tree->hasChildren());
  8448. bool hiddenRootArrayObject = isRootArrayObjectHidden(root, name, flags);
  8449. if (!hiddenRootArrayObject)
  8450. {
  8451. if (complex)
  8452. yaml.beginMap();
  8453. if (hasAttributes)
  8454. {
  8455. ForEach(*it)
  8456. {
  8457. const char *key = it->queryName()+1;
  8458. const char *val = it->queryValue();
  8459. yaml.writeAttribute(key, val, isSanitizedAndHidden(val, flags, true));
  8460. }
  8461. }
  8462. }
  8463. StringBuffer _content;
  8464. const char *content = nullptr; // to avoid uninitialized warning
  8465. bool isBinary = tree->isBinary(NULL);
  8466. bool isNull = true;
  8467. if (!hiddenRootArrayObject)
  8468. {
  8469. if (isBinary)
  8470. {
  8471. MemoryBuffer thislevelbin;
  8472. isNull = (!tree->getPropBin(NULL, thislevelbin))||(thislevelbin.length()==0);
  8473. if (!isNull)
  8474. JBASE64_Encode(thislevelbin.toByteArray(), thislevelbin.length(), _content, true);
  8475. content = _content.str();
  8476. }
  8477. else if (tree->isCompressed(NULL))
  8478. {
  8479. isNull = false; // can't be empty if compressed;
  8480. verifyex(tree->getProp(NULL, _content));
  8481. content = _content.str();
  8482. }
  8483. else
  8484. isNull = (NULL == (content = tree->queryProp(NULL)));
  8485. if (isNull && !root && !complex)
  8486. {
  8487. yaml.writeValue("null", false, false, false);
  8488. return;
  8489. }
  8490. }
  8491. Owned<IPropertyTreeIterator> sub = tree->getElements(hiddenRootArrayObject ? "__item__" : "*", 0 != (flags & YAML_SortTags) ? iptiter_sort : iptiter_null);
  8492. //note that detection of repeating elements relies on the fact that ptree elements
  8493. //of the same name will be grouped together
  8494. StringAttr seqname;
  8495. bool sequence = false;
  8496. ForEach(*sub)
  8497. {
  8498. IPropertyTree &element = sub->query();
  8499. bool first = false;
  8500. bool endprior = false;
  8501. sequence = checkInSequence(element, seqname, first, endprior);
  8502. if (endprior)
  8503. yaml.endSequence();
  8504. if (first)
  8505. yaml.beginSequence(hiddenRootArrayObject ? nullptr : element.queryName());
  8506. _toYAML(&element, yaml, flags, false, sequence);
  8507. }
  8508. if (sequence)
  8509. yaml.endSequence();
  8510. if (!isNull)
  8511. {
  8512. if (complex)
  8513. yaml.writeName("^");
  8514. //repeating/array/sequence items are implicitly elements, no need for tag
  8515. yaml.writeValue(content, isArrayItem ? false : true, isSanitizedAndHidden(content, flags, false), isBinary);
  8516. }
  8517. if (!hiddenRootArrayObject && complex)
  8518. yaml.endMap();
  8519. }
  8520. static void _toYAML(const IPropertyTree *tree, IIOStream &out, unsigned indent, byte flags, bool root=false, bool isArrayItem=false)
  8521. {
  8522. YAMLEmitter yaml(out, indent);
  8523. _toYAML(tree, yaml, flags, true, false);
  8524. }
  8525. jlib_decl StringBuffer &toYAML(const IPropertyTree *tree, StringBuffer &ret, unsigned indent, byte flags)
  8526. {
  8527. CStringBufferMarkupIOAdapter adapter(ret);
  8528. _toYAML(tree->queryBranch(NULL), adapter, indent, flags, true);
  8529. return ret;
  8530. }
  8531. void toYAML(const IPropertyTree *tree, IIOStream &out, unsigned indent, byte flags)
  8532. {
  8533. _toYAML(tree, out, indent, flags, true);
  8534. }
  8535. void printYAML(const IPropertyTree *tree, unsigned indent, unsigned flags)
  8536. {
  8537. StringBuffer yaml;
  8538. toYAML(tree, yaml, indent, flags);
  8539. printf("%s", yaml.str());
  8540. }
  8541. void dbglogYAML(const IPropertyTree *tree, unsigned indent, unsigned flags)
  8542. {
  8543. StringBuffer yaml;
  8544. toYAML(tree, yaml, indent, flags);
  8545. DBGLOG("%s", yaml.str());
  8546. }
  8547. void saveYAML(const char *filename, const IPropertyTree *tree, unsigned indent, unsigned flags)
  8548. {
  8549. OwnedIFile ifile = createIFile(filename);
  8550. saveYAML(*ifile, tree, indent, flags);
  8551. }
  8552. void saveYAML(IFile &ifile, const IPropertyTree *tree, unsigned indent, unsigned flags)
  8553. {
  8554. OwnedIFileIO ifileio = ifile.open(IFOcreate);
  8555. if (!ifileio)
  8556. throw MakeStringException(0, "saveXML: could not find %s to open", ifile.queryFilename());
  8557. saveYAML(*ifileio, tree, indent, flags);
  8558. }
  8559. void saveYAML(IFileIO &ifileio, const IPropertyTree *tree, unsigned indent, unsigned flags)
  8560. {
  8561. Owned<IIOStream> stream = createIOStream(&ifileio);
  8562. stream.setown(createBufferedIOStream(stream));
  8563. saveYAML(*stream, tree, indent, flags);
  8564. }
  8565. void saveYAML(IIOStream &stream, const IPropertyTree *tree, unsigned indent, unsigned flags)
  8566. {
  8567. toYAML(tree, stream, indent, flags);
  8568. }
  8569. jlib_decl IPropertyTree * queryCostsConfiguration()
  8570. {
  8571. return queryComponentConfig().queryPropTree("costs");
  8572. }