jptree.cpp 257 KB

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