jptree.cpp 220 KB

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