123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383 |
- /*##############################################################################
- HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ############################################################################## */
- #include "platform.h"
- #include "jarray.hpp"
- #include "jdebug.hpp"
- #include "jhash.hpp"
- #include "jmutex.hpp"
- #include "jexcept.hpp"
- #include "jlzw.hpp"
- #include "jregexp.hpp"
- #include "jstring.hpp"
- #include <algorithm>
- #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
- #undef new
- #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
- #endif
- #define MAKE_LSTRING(name,src,length) \
- const char *name = (const char *) alloca((length)+1); \
- memcpy((char *) name, (src), (length)); \
- *(char *) (name+(length)) = '\0';
- #include "jfile.hpp"
- #include "jlog.hpp"
- #include "jptree.ipp"
- #define WARNLEGACYCOMPARE
- #define XMLTAG_CONTENT "<>"
- #undef UNIMPLEMENTED
- #define UNIMPLEMENTED throw MakeIPTException(-1, "UNIMPLEMENTED")
- #define CHECK_ATTRIBUTE(X) if (X && isAttribute(X)) throw MakeIPTException(PTreeExcpt_XPath_Unsupported, "Attribute usage invalid here");
- #define AMBIGUOUS_PATH(X,P) { StringBuffer buf; buf.append(X": ambiguous xpath \"").append(P).append("\""); throw MakeIPTException(PTreeExcpt_XPath_Ambiguity,"%s",buf.str()); }
- #define PTREE_COMPRESS_THRESHOLD (4*1024) // i.e. only use compress if > threshold
- #define PTREE_COMPRESS_BOTHER_PECENTAGE (80) // i.e. if it doesn't compress to <80 % of original size don't bother
- class NullPTreeIterator : implements IPropertyTreeIterator, public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- // IPropertyTreeIterator
- virtual bool first() override { return false; }
- virtual bool next() override { return false; }
- virtual bool isValid() override { return false; }
- virtual IPropertyTree & query() override { assertex(false); return *(IPropertyTree *)NULL; }
- } *nullPTreeIterator;
- IPropertyTreeIterator *createNullPTreeIterator() { return LINK(nullPTreeIterator); } // initialize in init mod below.
- //===================================================================
- #ifdef USE_READONLY_ATOMTABLE
- RONameTable *AttrStrUnionWithTable::roNameTable = nullptr;
- #endif
- static AtomRefTable *keyTable = nullptr;
- static AtomRefTable *keyTableNC = nullptr;
- static CriticalSection hashcrit;
- static CAttrValHashTable *attrHT = nullptr;
- static AttrValue **freelist = nullptr;
- static unsigned freelistmax = 0;
- static CLargeMemoryAllocator freeallocator((memsize_t)-1, 0x1000*sizeof(AttrValue), true);
- #ifdef USE_READONLY_ATOMTABLE
- static const char * roAttributes[] =
- {
- #include "jptree-attrs.hpp" // potentially auto-generated
- nullptr
- };
- void initializeRoTable()
- {
- for (const char **attr = roAttributes; *attr; attr++)
- {
- AttrStrUnionWithTable::roNameTable->find(*attr, true);
- }
- #ifdef TRACE_ATOM_SIZE
- // If you are wanting an idea of the savings from use of the RO hash table, it may be useful to reset
- // the counts here. But it's more correct to actually leave them in place.
- //AttrStrAtom::totsize = 0;
- //AttrStrAtom::maxsize = 0;
- #endif
- #ifdef _DEBUG
- for (const char **a = roAttributes; *a; a++)
- {
- // sanity check
- unsigned idx = AttrStrUnionWithTable::roNameTable->findIndex(*a,AttrStrC::getHash(*a));
- AttrStrC *val = AttrStrUnionWithTable::roNameTable->getIndex(idx);
- assert(val && val->eq(*a));
- }
- #endif
- }
- #endif
- MODULE_INIT(INIT_PRIORITY_JPTREE)
- {
- nullPTreeIterator = new NullPTreeIterator;
- #ifdef USE_READONLY_ATOMTABLE
- AttrStrUnionWithTable::roNameTable = new RONameTable;
- initializeRoTable();
- #endif
- keyTable = new AtomRefTable;
- keyTableNC = new AtomRefTable(true);
- attrHT = new CAttrValHashTable;
- return true;
- }
- MODULE_EXIT()
- {
- nullPTreeIterator->Release();
- delete attrHT;
- keyTable->Release();
- keyTableNC->Release();
- free(freelist);
- freelist = NULL;
- }
- static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
- {
- IPropertyTree *l = (IPropertyTree *) *ll;
- IPropertyTree *r = (IPropertyTree *) *rr;
- return stricmp(l->queryName(), r->queryName());
- };
- //////////////////
- unsigned ChildMap::getHashFromElement(const void *e) const
- {
- PTree &elem = (PTree &) (*(IPropertyTree *)e);
- return elem.queryHash();
- }
- unsigned ChildMap::numChildren()
- {
- SuperHashIteratorOf<IPropertyTree> iter(*this);
- if (!iter.first()) return 0;
- unsigned count = 0;
- do
- {
- PTree *element = (PTree *) &iter.query();
- if (element->value && element->value->isArray())
- count += element->value->elements();
- else
- ++count;
- }
- while (iter.next());
- return count;
- }
- IPropertyTreeIterator *ChildMap::getIterator(bool sort)
- {
- class CPTHashIterator : implements IPropertyTreeIterator, public CInterface
- {
- SuperHashIteratorOf<IPropertyTree> *hiter;
- public:
- IMPLEMENT_IINTERFACE;
- CPTHashIterator(SuperHashTable &table) { hiter = new SuperHashIteratorOf<IPropertyTree>(table); }
- ~CPTHashIterator() { hiter->Release(); }
- // IPropertyTreeIterator
- virtual bool first() override { return hiter->first(); }
- virtual bool next() override { return hiter->next(); }
- virtual bool isValid() override { return hiter->isValid(); }
- virtual IPropertyTree & query() override { return hiter->query(); }
- };
- class CPTArrayIterator : public ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>
- {
- IArrayOf<IPropertyTree> elems;
- public:
- CPTArrayIterator(IPropertyTreeIterator &iter) : ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>(elems)
- {
- ForEach(iter)
- elems.append(iter.get());
- elems.sort(comparePropTrees);
- }
- };
- IPropertyTreeIterator *baseIter = new CPTHashIterator(*this);
- if (!sort)
- return baseIter;
- IPropertyTreeIterator *it = new CPTArrayIterator(*baseIter);
- baseIter->Release();
- return it;
- }
- ///////////
- bool validateXMLTag(const char *name)
- {
- if (!isValidXPathStartChr(*name)) return false;
- ++name;
- while (*name != '\0')
- {
- if (!isValidXPathChr(*name)) return false;
- ++name;
- }
- return true;
- }
- class jlib_thrown_decl CPTreeException : implements IPTreeException, public CInterface
- {
- int errCode;
- StringBuffer errMsg;
- public:
- IMPLEMENT_IINTERFACE;
- CPTreeException(int _errCode, const char *_errMsg, va_list &args) __attribute__((format(printf,3,0))) : errCode(_errCode)
- {
- if (_errMsg)
- errMsg.valist_appendf(_errMsg, args);
- }
- StringBuffer &translateCode(StringBuffer &out) const
- {
- out.append("IPropertyTree: ");
- switch (errCode)
- {
- case PTreeExcpt_XPath_Ambiguity:
- return out.append("Ambiguous xpath used");
- case PTreeExcpt_XPath_ParseError:
- return out.append("xpath parse error");
- case PTreeExcpt_XPath_Unsupported:
- return out.append("unsupported xpath syntax used");
- case PTreeExcpt_InvalidTagName:
- return out.append("Invalid tag name");
- default:
- return out.append("UNKNOWN ERROR CODE: ").append(errCode);
- }
- }
- // IException
- int errorCode() const { return errCode; }
- StringBuffer &errorMessage(StringBuffer &out) const
- {
- return translateCode(out).append("\n").append(errMsg.str());
- }
- MessageAudience errorAudience() const { return MSGAUD_user; }
- };
- static IPTreeException *MakeIPTException(int code, const char *format, ...) __attribute__((format(printf,2,3)));
- static IPTreeException *MakeXPathException(const char *xpath, int code, size_t pos, const char *format, ...) __attribute__((format(printf,4,5)));
- IPTreeException *MakeIPTException(int code, const char *format, ...)
- {
- va_list args;
- va_start(args, format);
- IPTreeException *e = new CPTreeException(code, format, args);
- va_end(args);
- return e;
- }
- IPTreeException *MakeXPathException(const char *xpath, int code, size_t pos, const char *format, ...)
- {
- va_list args;
- va_start(args, format);
- StringBuffer s("XPath Exception: ");
- s.valist_appendf(format, args);
- va_end(args);
- #ifdef _DEBUG
- PrintStackReport();
- #endif
- const char *msg = "in xpath = ";
- s.append("\n").append(msg).append(xpath);
- s.append("\n").appendN((size32_t)(strlen(msg)+pos), ' ').append("^");
- return MakeIPTException(code, "%s", s.str());
- }
- inline static void readID(const char *&xxpath, bool started)
- {
- const char *xpath = xxpath;
- if (isValidXPathStartChr(*xpath) || (started && isValidXPathChr(*xpath)))
- {
- do
- {
- xpath++;
- } while (isValidXPathChr(*xpath));
- xxpath = xpath;
- }
- }
- inline static void readWildId(const char *&xpath, bool &wild)
- {
- wild = false;
- for (;;)
- {
- readID(xpath, wild);
- if ('*' != *xpath)
- break;
- wild = true;
- ++xpath;
- }
- }
- inline const char * readIndex(const char *xpath, StringAttr &index)
- {
- const char *start = xpath;
- do { xpath++; } while (isdigit(*xpath));
- index.set(start, (xpath - start));
- return xpath;
- }
- inline static void readWildIdIndex(const char *&xpath, bool &wild)
- {
- const char *_xpath = xpath;
- readWildId(xpath, wild);
- if ('[' == *xpath) // check for local index not iterative qualifier.
- {
- const char *end = xpath+1;
- if (isdigit(*end)) {
- StringAttr index;
- end = readIndex(end, index);
- if (']' != *end)
- throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
- xpath = end+1;
- }
- }
- }
- inline static unsigned getTailIdLength(const char *xxpath, unsigned xxpathlength)
- {
- const char *xpath = xxpath+xxpathlength;
- const char *end = xpath;
- while (xpath != xxpath)
- {
- --xpath;
- if (!isValidXPathChr(*xpath)) break;
- }
- if (!isAttribute(xpath) && xpath != xxpath) ++xpath;
- return end-xpath;
- }
- const char *splitXPathUQ(const char *xpath, StringBuffer &path)
- {
- size32_t xpathSize = (size32_t) strlen(xpath);
- size32_t idSize = getTailIdLength(xpath, xpathSize);
- path.append(xpathSize-idSize, xpath);
- return xpath + (xpathSize-idSize);
- }
- const char *splitXPathX(const char *xpath)
- {
- size32_t xpathSize = (size32_t) strlen(xpath);
- size32_t idSize = getTailIdLength(xpath, xpathSize);
- return xpath + (xpathSize-idSize);
- }
- // similar to above, splitXPathUQ doesn't split if qualified
- const char *splitXPath(const char *xpath, StringBuffer &headPath)
- {
- StringBuffer path;
- const char *end = xpath+strlen(xpath);
- const char *prop = end;
- bool quote = false;
- bool braced = false;
- while (xpath != prop)
- {
- --prop;
- if (*prop == '"')
- {
- if (quote) quote = false;
- else quote = true;
- }
- else if (*prop == ']' && !quote)
- {
- assertex(!braced);
- braced = true;
- }
- else if (*prop == '[' && !quote)
- {
- assertex(braced);
- braced = false;
- }
- else if (*prop == '/' && !quote && !braced)
- {
- ++prop;
- break;
- }
- }
- if (prop == end)
- return NULL;
- else if (xpath != prop)
- {
- size32_t ps = prop-xpath-1;
- headPath.append(ps, xpath);
- }
- return prop;
- }
- const char *queryNextUnquoted(const char *str, char c)
- {
- bool quote = false;
- for (;;)
- {
- char next = *str;
- if (next == '\0')
- return NULL;
- if ('"' == next)
- quote = !quote;
- else if (c == next && !quote)
- return str;
- ++str;
- }
- }
- const char *queryHead(const char *xpath, StringBuffer &head)
- {
- if (!xpath) return NULL;
- const char *start = xpath;
- bool quote = false;
- bool braced = false;
- for (;;)
- {
- if (*xpath == '\0')
- return NULL;
- ++xpath;
- char next = *xpath;
- if ('"' == next)
- quote = !quote;
- else if (next == ']' && !quote)
- {
- assertex(braced);
- braced = false;
- }
- else if (next == '[' && !quote)
- {
- assertex(!braced);
- braced = true;
- }
- else if (next == '/' && !quote && !braced)
- {
- if ('/' == *start) // so leading '//'
- return start;
- else if ('/' == *(xpath+1)) // in middle of path
- {
- head.append(xpath-start, start);
- return xpath;
- }
- break;
- }
- }
- head.append(xpath-start, start);
- return xpath+1;
- }
- ///////////////////
- class SeriesPTIterator : implements IPropertyTreeIterator, public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- SeriesPTIterator() : current(NULL), cp(0)
- {
- }
- void addIterator(IPropertyTreeIterator *iter) { iters.append(*iter); }
- // IPropertyTreeIterator impl.
- virtual bool first() override
- {
- cp = 0;
- iterCount = iters.ordinality();
- if (nextIterator())
- return true;
- else
- return false;
- }
- virtual bool next() override
- {
- while (currentIter)
- {
- if (currentIter->next())
- {
- current = ¤tIter->query();
- return true;
- }
- if (nextIterator())
- return true;
- }
- current = NULL;
- return false;
- }
- virtual bool isValid() override { return (NULL != current); }
- virtual IPropertyTree & query() override { assertex(current); return *current; }
- private:
- bool nextIterator()
- {
- while (cp<iterCount)
- {
- currentIter = (IPropertyTreeIterator *) &iters.item(cp++);
- if (currentIter->first())
- {
- current = ¤tIter->query();
- return true;
- }
- }
- current = NULL;
- currentIter = NULL;
- return false;
- }
- IArray iters;
- IPropertyTreeIterator *currentIter;
- IPropertyTree *current;
- unsigned cp, iterCount;
- };
- ///////////////////
- CPTValue::CPTValue(size32_t size, const void *data, bool binary, bool raw, bool _compressed)
- {
- compressed = _compressed;
- if (!raw && binary && size > PTREE_COMPRESS_THRESHOLD)
- {
- unsigned newSize = size * PTREE_COMPRESS_BOTHER_PECENTAGE / 100;
- void *newData = NULL;
- ICompressor *compressor = NULL;
- try
- {
- newData = malloc(sizeof(size32_t) + newSize);
- compressor = createLZWCompressor();
- compressor->open(((char *)newData) + sizeof(size32_t), newSize);
- if (compressor->write(data, size)==size)
- {
- compressor->close();
- memcpy(newData, &size, sizeof(size32_t));
- newSize = sizeof(size32_t) + compressor->buflen();
- compressed = true;
- set(newSize, newData);
- }
- free(newData);
- compressor->Release();
- }
- catch (...)
- {
- if (newData)
- free(newData);
- if (compressor) compressor->Release();
- throw;
- }
- }
- if (raw || !compressed)
- set(size, data);
- }
- static void *uncompress(const void *src, size32_t &sz)
- {
- IExpander *expander = NULL;
- void *uncompressedValue = NULL;
- try
- {
- memcpy(&sz, src, sizeof(size32_t));
- assertex(sz);
- expander = createLZWExpander();
- src = ((const char *)src) + sizeof(size32_t);
- uncompressedValue = malloc(sz);
- assertex(uncompressedValue);
- expander->init(src);
- expander->expand(uncompressedValue);
- expander->Release();
- return uncompressedValue;
- }
- catch (...)
- {
- if (expander) expander->Release();
- if (uncompressedValue) free(uncompressedValue);
- throw;
- }
- }
- const void *CPTValue::queryValue() const
- {
- if (compressed)
- {
- size32_t sz;
- void *uncompressedValue = uncompress(get(), sz);
- ((MemoryAttr *)this)->setOwn(sz, uncompressedValue);
- compressed = false;
- }
- return get();
- }
- void CPTValue::serialize(MemoryBuffer &tgt)
- {
- //Retain backward compatibility for the serialization format.
- size32_t serialLen = (size32_t)length();
- tgt.append(serialLen);
- if (serialLen)
- {
- tgt.append(compressed);
- tgt.append(serialLen, get());
- }
- }
- void CPTValue::deserialize(MemoryBuffer &src)
- {
- size32_t sz;
- src.read(sz);
- if (sz)
- {
- src.read(compressed);
- set(sz, src.readDirect(sz));
- }
- else
- {
- compressed = false;
- clear();
- }
- }
- MemoryBuffer &CPTValue::getValue(MemoryBuffer &tgt, bool binary) const
- {
- if (compressed)
- {
- size32_t sz;
- void *uncompressedValue = uncompress(get(), sz);
- if (!binary) sz -= 1;
- tgt.append(sz, uncompressedValue);
- if (uncompressedValue)
- free(uncompressedValue);
- }
- else
- {
- if (binary)
- tgt.append((size32_t)length(), get());
- else
- tgt.append((size32_t)length()-1, get());
- }
- return tgt;
- }
- StringBuffer &CPTValue::getValue(StringBuffer &tgt, bool binary) const
- {
- if (compressed)
- {
- size32_t sz;
- void *uncompressedValue = NULL;
- try
- {
- uncompressedValue = uncompress(get(), sz);
- if (!binary) sz -= 1;
- tgt.append(sz, (const char *)uncompressedValue);
- free(uncompressedValue);
- }
- catch (IException *)
- {
- if (uncompressedValue) free(uncompressedValue);
- throw;
- }
- }
- else
- {
- if (binary) // this should probably be an assert?
- tgt.append((size32_t)length(), (const char *)get());
- else if (length())
- tgt.append((size32_t)length()-1, (const char *)get());
- }
- return tgt;
- }
- size32_t CPTValue::queryValueSize() const
- {
- if (compressed)
- {
- size32_t sz;
- memcpy(&sz, get(), sizeof(size32_t));
- return sz;
- }
- else
- return (size32_t)length();
- }
- ///////////////////
- PTree::PTree(byte _flags, IPTArrayValue *_value, ChildMap *_children)
- {
- flags = _flags;
- children = LINK(_children);
- value = _value;
- }
- PTree::~PTree()
- {
- if (value) delete value;
- ::Release(children);
- }
- IPropertyTree *PTree::queryChild(unsigned index)
- {
- if (!value) return NULL;
- if (!value->isArray()) return this;
- IPropertyTree *v = value->queryElement(index);
- return v;
- }
- aindex_t PTree::findChild(IPropertyTree *child, bool remove)
- {
- if (value && value->isArray())
- {
- unsigned i;
- for (i=0; i<value->elements(); i++)
- {
- IPropertyTree *_child = value->queryElement(i);
- if (_child == child)
- {
- if (remove)
- {
- assertex(value);
- value->removeElement(i);
- }
- return i;
- }
- }
- }
- else if (children)
- {
- IPropertyTree *_child = children->query(child->queryName());
- if (_child == child)
- {
- if (remove)
- children->removeExact(_child);
- return 0;
- }
- else if (_child)
- {
- PTree *__child = (PTree *) _child;
- return __child->findChild(child, remove);
- }
- }
- return NotFound;
- }
- ChildMap *PTree::checkChildren() const
- {
- return children;
- }
- void PTree::setLocal(size32_t l, const void *data, bool _binary)
- {
- if (value) delete value;
- if (l)
- value = new CPTValue(l, data, _binary);
- else
- value = NULL;
- if (_binary)
- IptFlagSet(flags, ipt_binary);
- else
- IptFlagClr(flags, ipt_binary);
- }
- void PTree::appendLocal(size32_t l, const void *data, bool binary)
- {
- if (0 == l) return;
- MemoryBuffer mb;
- if (value)
- {
- assertex(!value->isArray());
- assertex(binary == IptFlagTst(flags, ipt_binary));
- value->getValue(mb, binary);
- mb.append(l, data);
- delete value;
-
- l = mb.length();
- data = mb.toByteArray();
- }
- if (l)
- value = new CPTValue(l, data, binary);
- else
- value = NULL;
- if (binary)
- IptFlagSet(flags, ipt_binary);
- else
- IptFlagClr(flags, ipt_binary);
- }
- // IPropertyTree impl.
- bool PTree::hasProp(const char * xpath) const
- {
- const char *prop = splitXPathX(xpath);
- if (isAttribute(prop)) // JCS - note no wildcards on attributes
- {
- if (prop != xpath)
- {
- MAKE_LSTRING(path, xpath, prop-xpath);
- Owned<IPropertyTreeIterator> iter = getElements(path);
- if (iter->first())
- {
- do
- {
- IPropertyTree &branch = iter->query();
- if (branch.hasProp(prop))
- return true;
- }
- while (iter->next());
- }
- return false;
- }
- else
- return nullptr != findAttribute(xpath);
- }
- else
- {
- IPropertyTreeIterator *iter = getElements(xpath);
- bool res = iter->first();
- iter->Release();
- return res;
- }
- }
- const char *PTree::queryProp(const char *xpath) const
- {
- if (!xpath)
- {
- if (!value) return NULL;
- return (const char *) value->queryValue();
- }
- else if (isAttribute(xpath))
- return getAttributeValue(xpath);
- else
- {
- const char *prop = splitXPathX(xpath);
- if (isAttribute(prop))
- {
- MAKE_LSTRING(path, xpath, prop-xpath);
- IPropertyTree *branch = queryPropTree(path);
- if (!branch) return NULL;
- return branch->queryProp(prop);
- }
- else
- {
- IPropertyTree *branch = queryPropTree(xpath);
- if (!branch) return NULL;
- return branch->queryProp(NULL);
- }
- }
- }
- bool PTree::getProp(const char *xpath, StringBuffer &ret) const
- {
- if (!xpath)
- {
- if (!value) return false;
- value->getValue(ret, IptFlagTst(flags, ipt_binary));
- return true;
- }
- else if (isAttribute(xpath))
- {
- const char *value = getAttributeValue(xpath);
- if (!value) return false;
- ret.append(value);
- return true;
- }
- else
- {
- const char *prop = splitXPathX(xpath);
- if (isAttribute(prop))
- {
- MAKE_LSTRING(path, xpath, prop-xpath)
- IPropertyTree *branch = queryPropTree(path);
- if (!branch) return false;
- return branch->getProp(prop, ret);
- }
- else
- {
- IPropertyTree *branch = queryPropTree(xpath);
- if (!branch) return false;
- return branch->getProp(NULL, ret);
- }
- }
- }
- void PTree::setProp(const char *xpath, const char *val)
- {
- if (!xpath || '\0' == *xpath)
- {
- if (!val)
- {
- if (value) delete value;
- value = NULL;
- }
- else
- {
- size32_t l=(size32_t)strlen(val);
- if (!l)
- {
- if (value) delete value;
- value = NULL;
- }
- else
- setLocal(l+1, val);
- }
- }
- else if (isAttribute(xpath))
- {
- if (!val)
- removeAttribute(xpath);
- else
- setAttribute(xpath, val);
- }
- else
- {
- const char *prop;
- IPropertyTree *branch = splitBranchProp(xpath, prop, true);
- if (isAttribute(prop))
- branch->setProp(prop, val);
- else
- {
- if (val)
- {
- IPropertyTree *propBranch = queryCreateBranch(branch, prop);
- propBranch->setProp(NULL, val);
- }
- else
- branch->removeProp(prop);
- }
- }
- }
- aindex_t PTree::getChildMatchPos(const char *xpath)
- {
- Owned<IPropertyTreeIterator> childIter = getElements(xpath);
- if (!childIter->first())
- return (aindex_t)-1;
- IPropertyTree &childMatch = childIter->query();
- if (childIter->next())
- AMBIGUOUS_PATH("addPropX", xpath);
- if (value)
- if (value->isArray())
- return findChild(&childMatch);
- else
- return 0;
- else
- return 0;
- }
- void PTree::resolveParentChild(const char *xpath, IPropertyTree *&parent, IPropertyTree *&child, StringAttr &path, StringAttr &qualifier)
- {
- parent = child = NULL;
- if (!xpath)
- throw MakeIPTException(-1, "No path to resolve parent from");
- const char *end = xpath+strlen(xpath);
- const char *prop = end;
- while (prop != xpath && *(prop-1) != '/')
- --prop;
- size32_t ps = prop-xpath;
- if (ps)
- {
- path.set(xpath, ps);
- Owned<IPropertyTreeIterator> pathIter = getElements(path);
- if (!pathIter->first())
- throw MakeIPTException(-1, "resolveParentChild: path not found %s", xpath);
- IPropertyTree *currentPath = NULL;
- bool multiplePaths = false;
- bool multipleChildMatches = false;
- for (;;)
- {
- // JCSMORE - a bit annoying has to be done again once path has been established
- currentPath = &pathIter->query();
- Owned<IPropertyTreeIterator> childIter = currentPath->getElements(prop);
- if (childIter->first())
- {
- child = &childIter->query();
- if (parent)
- AMBIGUOUS_PATH("resolveParentChild", xpath);
- if (!multipleChildMatches && childIter->next())
- multipleChildMatches = true;
- parent = currentPath;
- }
- if (pathIter->next())
- multiplePaths = true;
- else break;
- }
- if (!parent)
- {
- if (multiplePaths) // i.e. no unique path to child found and multiple parent paths
- AMBIGUOUS_PATH("resolveParentChild", xpath);
- parent = currentPath;
- }
- if (multipleChildMatches)
- child = NULL; // single parent, but no single child.
- path.set(prop);
- const char *pstart = prop;
- bool wild;
- readWildId(prop, wild);
- size32_t s = prop-pstart;
- if (wild)
- throw MakeXPathException(pstart, PTreeExcpt_XPath_ParseError, s-1, "Wildcards not permitted on add");
- assertex(s);
- path.set(pstart, s);
- qualifier.set(prop);
- }
- else
- {
- assertex(prop && *prop);
- parent = this;
- const char *pstart = prop;
- bool wild;
- readWildId(prop, wild);
- assertex(!wild);
- size32_t s = prop-pstart;
- if (*prop && *prop != '[')
- throw MakeXPathException(pstart, PTreeExcpt_XPath_ParseError, s, "Qualifier expected e.g. [..]");
- path.set(pstart, s);
- if (checkChildren())
- child = children->query(path);
- if (child)
- qualifier.set(prop);
- else
- qualifier.clear();
- }
- }
- void PTree::addProp(const char *xpath, const char *val)
- {
- if (!xpath || '\0' == *xpath)
- addLocal((size32_t)strlen(val)+1, val);
- else if (isAttribute(xpath))
- setAttribute(xpath, val);
- else if ('[' == *xpath)
- {
- aindex_t pos = getChildMatchPos(xpath);
- if ((aindex_t) -1 == pos)
- throw MakeIPTException(-1, "addProp: qualifier unmatched %s", xpath);
- addLocal((size32_t)strlen(val)+1, val, false, pos);
- }
- else
- {
- IPropertyTree *parent, *child;
- StringAttr path, qualifier;
- resolveParentChild(xpath, parent, child, path, qualifier);
- if (parent != this)
- parent->addProp(path, val);
- else if (child)
- child->addProp(qualifier, val);
- else
- setProp(path, val);
- }
- }
- void PTree::appendProp(const char *xpath, const char *val)
- {
- if (!xpath || '\0' == *xpath)
- appendLocal((size_t)strlen(val)+1, val, false);
- else if (isAttribute(xpath))
- {
- StringBuffer newVal;
- getProp(xpath, newVal);
- newVal.append(val);
- setAttribute(xpath, newVal.str());
- }
- else if ('[' == *xpath)
- {
- aindex_t pos = getChildMatchPos(xpath);
- if ((aindex_t) -1 == pos)
- throw MakeIPTException(-1, "appendProp: qualifier unmatched %s", xpath);
- appendLocal((size_t)strlen(val)+1, val, false);
- }
- else
- {
- IPropertyTree *parent, *child;
- StringAttr path, qualifier;
- resolveParentChild(xpath, parent, child, path, qualifier);
- if (parent != this)
- parent->appendProp(path, val);
- else if (child)
- child->appendProp(qualifier, val);
- else
- setProp(path, val);
- }
- }
- bool PTree::getPropBool(const char *xpath, bool dft) const
- {
- const char *val = queryProp(xpath);
- if (val && *val)
- return strToBool(val);
- else
- return dft;
- }
- __int64 PTree::getPropInt64(const char *xpath, __int64 dft) const
- {
- if (!xpath)
- {
- if (!value) return dft;
- else
- {
- const char *v = (const char *)value->queryValue();
- if (!v || !*v) return dft;
- else return _atoi64(v);
- }
- }
- else if (isAttribute(xpath))
- {
- const char *v = getAttributeValue(xpath);
- if (!v || !*v) // intentional return dft if attribute equals ""
- return dft;
- return _atoi64(v);
- }
- else
- {
- const char *prop = splitXPathX(xpath);
- if (isAttribute(prop))
- {
- MAKE_LSTRING(path, xpath, prop-xpath);
- IPropertyTree *branch = queryPropTree(path);
- if (!branch) return dft;
- return branch->getPropInt64(prop, dft);
- }
- else
- {
- IPropertyTree *branch = queryPropTree(xpath);
- if (!branch) return dft;
- return branch->getPropInt64(NULL, dft);
- }
- }
- }
- void PTree::setPropInt64(const char * xpath, __int64 val)
- {
- if (!xpath || '\0' == *xpath)
- {
- char buf[23];
- numtostr(buf, val);
- setLocal((size32_t)strlen(buf)+1, buf);
- }
- else if (isAttribute(xpath))
- {
- char buf[23];
- numtostr(buf, val);
- setAttribute(xpath, buf);
- }
- else
- {
- const char *prop;
- IPropertyTree *branch = splitBranchProp(xpath, prop, true);
- if (isAttribute(prop))
- branch->setPropInt64(prop, val);
- else
- {
- IPropertyTree *propBranch = queryCreateBranch(branch, prop);
- propBranch->setPropInt64(NULL, val);
- }
- }
- }
- void PTree::addPropInt64(const char *xpath, __int64 val)
- {
- if (!xpath || '\0' == *xpath)
- {
- char buf[23];
- numtostr(buf,val);
- addLocal((size32_t)strlen(buf)+1, buf);
- }
- else if (isAttribute(xpath))
- {
- char buf[23];
- numtostr(buf, val);
- setAttribute(xpath, buf);
- }
- else if ('[' == *xpath)
- {
- char buf[23];
- numtostr(buf, val);
- aindex_t pos = getChildMatchPos(xpath);
- if ((aindex_t) -1 == pos)
- throw MakeIPTException(-1, "addPropInt64: qualifier unmatched %s", xpath);
- addLocal((size32_t)strlen(buf)+1, buf, false, pos);
- }
- else
- {
- IPropertyTree *parent, *child;
- StringAttr path, qualifier;
- resolveParentChild(xpath, parent, child, path, qualifier);
- if (parent != this)
- parent->addPropInt64(path, val);
- else if (child)
- child->addPropInt64(qualifier, val);
- else
- setPropInt64(path, val);
- }
- }
- int PTree::getPropInt(const char *xpath, int dft) const
- {
- return (int) getPropInt64(xpath, dft); // underlying type always __int64 (now)
- }
- void PTree::setPropInt(const char *xpath, int val)
- {
- setPropInt64(xpath, val); // underlying type always __int64 (now)
- }
- void PTree::addPropInt(const char *xpath, int val)
- {
- addPropInt64(xpath, val); // underlying type always __int64 (now)
- }
- bool PTree::isCompressed(const char *xpath) const
- {
- if (!xpath)
- return (value && value->isCompressed());
- else if (isAttribute(xpath))
- return false;
- else
- {
- const char *prop = splitXPathX(xpath);
- if (prop && '\0' != *prop && !isAttribute(prop))
- {
- IPropertyTree *branch = queryPropTree(xpath);
- if (branch)
- return branch->isCompressed(prop);
- }
- }
- return false;
- }
- bool PTree::isBinary(const char *xpath) const
- {
- if (!xpath)
- return IptFlagTst(flags, ipt_binary);
- else if (isAttribute(xpath)) // still positing that attr cannot be binary for now.
- return false;
- else
- {
- const char *prop = splitXPathX(xpath);
- if (prop && '\0' != *prop && !isAttribute(prop))
- {
- IPropertyTree *branch = queryPropTree(xpath);
- if (branch)
- return branch->isBinary(NULL);
- }
- }
- return false;
- }
- bool PTree::renameTree(IPropertyTree *child, const char *newName) // really here for hook for SDS (can substationally optimize remote action)
- {
- if (0==strcmp(newName, child->queryName()) && NotFound!=findChild(child)) return false;
- Linked<IPropertyTree> tmp = child;
- if (removeTree(child))
- {
- addPropTree(newName, child);
- tmp.getClear(); // addPropTree has taken ownership.
- return true;
- }
- return false;
- }
- bool PTree::renameProp(const char *xpath, const char *newName)
- {
- if (!xpath || '\0' == *xpath)
- throw MakeIPTException(-1, "renameProp: cannot rename self, renameProp has to rename in context of a parent");
- if (strcmp(xpath,"/")==0) // rename of self allowed assuming no parent
- setName(newName);
- else if ('[' == *xpath)
- UNIMPLEMENTED;
- else if (isAttribute(xpath))
- {
- StringBuffer val;
- if (!getProp(xpath, val))
- return false;
- removeProp(xpath);
- addProp(newName, val.str());
- }
- else
- {
- StringBuffer path;
- const char *prop = splitXPath(xpath, path);
- assertex(prop);
- if (path.length())
- {
- Owned<IPropertyTreeIterator> iter = getElements(path.str());
- if (!iter->first())
- return false;
- IPropertyTree &branch = iter->query();
- if (iter->next())
- AMBIGUOUS_PATH("renameProp", xpath);
- return branch.renameProp(prop, newName);
- }
- else
- {
- IPropertyTree *old = queryPropTree(xpath);
- if (!old)
- return false;
- return renameTree(old, newName);
- }
- }
- return true;
- }
- bool PTree::getPropBin(const char *xpath, MemoryBuffer &ret) const
- {
- CHECK_ATTRIBUTE(xpath);
- if (!xpath)
- {
- if (!value) return true; // exists, but no value
- value->getValue(ret, IptFlagTst(flags, ipt_binary));
- return true;
- }
- else
- {
- const char *prop = splitXPathX(xpath);
- if (isAttribute(prop))
- {
- MAKE_LSTRING(path, xpath, prop-xpath);
- IPropertyTree *branch = queryPropTree(path);
- if (!branch) return false;
- return branch->getPropBin(prop, ret);
- }
- else
- {
- IPropertyTree *branch = queryPropTree(xpath);
- if (!branch) return false;
- return branch->getPropBin(NULL, ret);
- }
- }
- }
- void PTree::setPropBin(const char * xpath, size32_t size, const void *data)
- {
- CHECK_ATTRIBUTE(xpath);
- if (!xpath || '\0' == *xpath)
- setLocal(size, data, true);
- else
- {
- const char *prop;
- IPropertyTree *branch = splitBranchProp(xpath, prop, true);
- if (isAttribute(prop))
- branch->setPropBin(prop, size, data);
- else
- {
- IPropertyTree *propBranch = queryCreateBranch(branch, prop);
- propBranch->setPropBin(NULL, size, data);
- }
- }
- }
- void PTree::addPropBin(const char *xpath, size32_t size, const void *data)
- {
- CHECK_ATTRIBUTE(xpath);
- if (!xpath || '\0' == *xpath)
- addLocal(size, data, true);
- else if ('[' == *xpath)
- {
- aindex_t pos = getChildMatchPos(xpath);
- if ((aindex_t) -1 == pos)
- throw MakeIPTException(-1, "addPropBin: qualifier unmatched %s", xpath);
- addLocal(size, data, true, pos);
- }
- else
- {
- IPropertyTree *parent, *child;
- StringAttr path, qualifier;
- resolveParentChild(xpath, parent, child, path, qualifier);
- if (parent != this)
- parent->addPropBin(path, size, data);
- else if (child)
- child->addPropBin(qualifier, size, data);
- else
- setPropBin(path, size, data);
- }
- }
- void PTree::appendPropBin(const char *xpath, size32_t size, const void *data)
- {
- CHECK_ATTRIBUTE(xpath);
- if (!xpath || '\0' == *xpath)
- appendLocal(size, data, true);
- else if ('[' == *xpath)
- {
- aindex_t pos = getChildMatchPos(xpath);
- if ((aindex_t) -1 == pos)
- throw MakeIPTException(-1, "appendPropBin: qualifier unmatched %s", xpath);
- appendLocal(size, data, true);
- }
- else
- {
- IPropertyTree *parent, *child;
- StringAttr path, qualifier;
- resolveParentChild(xpath, parent, child, path, qualifier);
- if (parent != this)
- parent->appendPropBin(path, size, data);
- else if (child)
- child->appendPropBin(qualifier, size, data);
- else
- setPropBin(path, size, data);
- }
- }
- IPropertyTree *PTree::getPropTree(const char *xpath) const
- {
- IPropertyTree *tree = queryPropTree(xpath);
- return LINK(tree);
- }
- IPropertyTree *PTree::queryPropTree(const char *xpath) const
- {
- Owned<IPropertyTreeIterator> iter = getElements(xpath);
- IPropertyTree *element = NULL;
- if (iter->first())
- {
- element = &iter->query();
- if (iter->next())
- AMBIGUOUS_PATH("getProp",xpath);
- }
- return element;
- }
- void PTree::replaceSelf(IPropertyTree *val)
- {
- Owned<IAttributeIterator> aiter = getAttributes();
- StringArray attrs;
- ForEach (*aiter)
- attrs.append(aiter->queryName());
- ForEachItemIn(a, attrs)
- removeProp(attrs.item(a));
- ICopyArrayOf<IPropertyTree> elems;
- Owned<IPropertyTreeIterator> iter = getElements("*");
- ForEach(*iter)
- elems.append(iter->query());
- ForEachItemIn(e, elems)
- removeTree(&elems.item(e));
- aiter.setown(val->getAttributes());
- ForEach(*aiter)
- setProp(aiter->queryName(), aiter->queryValue());
- iter.setown(val->getElements("*"));
- ForEach(*iter)
- {
- IPropertyTree &node = iter->query();
- node.Link();
- addPropTree(node.queryName(), &node);
- }
- val->Release();
- }
- IPropertyTree *PTree::setPropTree(const char *xpath, IPropertyTree *val)
- {
- CHECK_ATTRIBUTE(xpath);
- if (NULL == xpath)
- {
- replaceSelf(val);
- return this;
- }
- else
- {
- StringAttr prop, qualifier;
- IPropertyTree *branch, *child;
- resolveParentChild(xpath, branch, child, prop, qualifier);
- if (branch == this)
- {
- IPropertyTree *_val = ownPTree(val);
- dbgassertex(QUERYINTERFACE(_val, PTree));
- PTree *__val = static_cast<PTree *>(_val);
- __val->setName(prop);
- addingNewElement(*_val, ANE_SET);
- if (!checkChildren()) createChildMap();
- children->set(prop, _val);
- return _val;
- }
- else
- return branch->setPropTree(prop, val);
- }
- }
- IPropertyTree *PTree::addPropTree(const char *xpath, IPropertyTree *val)
- {
- if (!xpath || '\0' == *xpath)
- throw MakeIPTException(PTreeExcpt_InvalidTagName, "Invalid xpath for property tree insertion specified");
- else
- {
- CHECK_ATTRIBUTE(xpath);
- const char *x = xpath;
- for (;;)
- {
- if (!*x++)
- {
- IPropertyTree *_val = ownPTree(val);
- dbgassertex(QUERYINTERFACE(_val, PTree));
- PTree *__val = static_cast<PTree *>(_val);
- /* NB: potentially param xpath is a reference to the existing name.
- * So fetch new name ptr after set.
- */
- __val->setName(xpath);
- xpath = __val->queryName();
- addingNewElement(*_val, -1);
- if (checkChildren())
- {
- IPropertyTree *child = children->query(xpath);
- if (child)
- {
- __val->setParent(this);
- dbgassertex(QUERYINTERFACE(child, PTree));
- PTree *tree = static_cast<PTree *>(child);
- if (tree->value && tree->value->isArray())
- tree->value->addElement(_val);
- else
- {
- IPTArrayValue *array = new CPTArray();
- array->addElement(LINK(child));
- array->addElement(_val);
- IPropertyTree *container = create(xpath, array);
- tree->setParent(this);
- children->replace(xpath, container);
- }
- return _val;
- }
- }
- else
- createChildMap();
- children->set(xpath, _val);
- return _val;
- }
- if ('/' == *x || '[' == *x)
- break;
- }
- IPropertyTree *parent, *child;
- StringAttr path, qualifier;
- resolveParentChild(xpath, parent, child, path, qualifier);
- if (parent != this)
- return parent->addPropTree(path, val);
- else
- {
- aindex_t pos = (aindex_t)-1;
- if (!qualifier.isEmpty())
- {
- pos = ((PTree *)child)->getChildMatchPos(qualifier);
- if ((aindex_t) -1 == pos)
- throw MakeIPTException(-1, "addPropTree: qualifier unmatched %s", xpath);
- }
- IPropertyTree *_val = ownPTree(val);
- dbgassertex(QUERYINTERFACE(_val, PTree));
- PTree *__val = static_cast<PTree *>(_val);
- __val->setName(path);
- addingNewElement(*_val, pos);
- if (child)
- {
- __val->setParent(this);
- dbgassertex(QUERYINTERFACE(child, PTree));
- PTree *tree = static_cast<PTree *>(child);
- if (tree->value && tree->value->isArray())
- {
- if ((aindex_t) -1 == pos)
- tree->value->addElement(_val);
- else
- tree->value->setElement(pos, _val);
- }
- else
- {
- IPTArrayValue *array = new CPTArray();
- array->addElement(LINK(child));
- assertex((aindex_t) -1 == pos || 0 == pos);
- if ((aindex_t) -1 == pos)
- array->addElement(_val);
- else
- array->setElement(0, _val);
- IPropertyTree *container = create(path, array);
- tree->setParent(this);
- children->replace(path, container);
- }
- }
- else
- {
- if (!checkChildren()) createChildMap();
- children->set(path, _val);
- }
- return _val;
- }
- }
- }
- bool PTree::removeTree(IPropertyTree *child)
- {
- if (child == this)
- throw MakeIPTException(-1, "Cannot remove self");
- if (children)
- {
- Owned<IPropertyTreeIterator> iter = children->getIterator(false);
- if (iter->first())
- {
- do
- {
- PTree *element = (PTree *) &iter->query();
- if (element == child)
- return children->removeExact(element);
- if (element->value && element->value->isArray())
- {
- Linked<PTree> tmp = (PTree*) child;
- aindex_t i = element->findChild(child, true);
- if (NotFound != i)
- {
- removingElement(child, i);
- if (0 == element->value->elements())
- children->removeExact(element);
- return true;
- }
- }
- }
- while (iter->next());
- }
- }
- return false;
- }
- bool PTree::removeProp(const char *xpath)
- {
- if (xpath && isAttribute(xpath))
- return removeAttribute(xpath);
- StringBuffer path;
- const char *prop = splitXPath(xpath, path);
- if (!prop)
- throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Invalid xpath for property deletion");
- if (path.length())
- {
- Owned<IPropertyTreeIterator> iter = getElements(path.str());
- if (!iter)
- return false;
-
- bool res = false;
- if (iter->first())
- {
- do
- {
- IPropertyTree *branch = &iter->query();
- if (branch) {
- res = branch->removeProp(prop);
- if (res)
- break; // deleted first may be another
- }
- }
- while (iter->next());
- }
- return res;
- }
- else
- {
- if (!queryNextUnquoted(xpath, '[') && !strchr(prop, '*')) // have to work hard to locate qualified prop tree from parent.
- {
- if (!checkChildren()) return false;
- return children->remove(prop); // NB: might be multivalued.
- }
- const char *xxpath = prop;
- readID(xxpath, false);
- const char *idEnd = xxpath;
- if ('[' == *xxpath)
- {
- ++xxpath;
- const char *digitStart = xxpath;
- while (*xxpath && ']' != *xxpath && isdigit(*xxpath)) xxpath++;
- assertex(*xxpath != '\0');
- if (']' == *xxpath) // so it's a digit index!
- {
- StringAttr id(prop, idEnd-prop);
- PTree *child = children?(PTree *)children->query(id):NULL;
- if (child)
- {
- if (child->value && child->value->isArray() && child->value->elements()>1)
- {
- StringAttr digit(digitStart, xxpath-digitStart);
- unsigned i = atoi(digit);
- if (i && i <= child->value->elements())
- {
- removingElement(child->value->queryElement(i-1), i-1);
- child->value->removeElement(i-1);
- return true;
- }
- }
- else
- return children->removeExact(child);
- }
- return false;
- }
- }
- // JCSMORE - This is ridiculous for qualifier have to iterate to find match ok, but then finding where that *was* gees!
- Owned <IPropertyTreeIterator> iter = getElements(prop);
- if (!iter->first())
- return false;
- IPropertyTree *match = &iter->query();
- #if 0 // intentionally removes first encountered
- if (iter->next())
- {
- AMBIGUOUS_PATH("removeProp",xpath);
- }
- #endif
- return removeTree(match);
- }
- return false;
- }
- aindex_t PTree::queryChildIndex(IPropertyTree *child)
- {
- return findChild(child);
- }
- StringBuffer &PTree::getName(StringBuffer &ret) const
- {
- ret.append(queryName());
- return ret;
- }
- typedef CopyReferenceArrayOf<AttrValue> AttrArray;
- IAttributeIterator *PTree::getAttributes(bool sorted) const
- {
- class CAttributeIterator : implements IAttributeIterator, public CInterface
- {
- Linked<const PTree> parent;
- AttrValue *cur = nullptr;
- public:
- IMPLEMENT_IINTERFACE;
- CAttributeIterator(const PTree *_parent) : parent(_parent)
- {
- }
- // IAttributeIterator impl.
- virtual bool first() override
- {
- cur = parent->getNextAttribute(nullptr);
- return cur ? true : false;
- }
- virtual bool next() override
- {
- cur = parent->getNextAttribute(cur);
- return cur ? true : false;
- }
- virtual bool isValid() override { return cur ? true : false; }
- virtual const char *queryName() const override
- {
- return cur->key.get();
- }
- virtual const char *queryValue() const override
- {
- return cur->value.get();
- }
- virtual StringBuffer &getValue(StringBuffer &out) override
- {
- out.append(queryValue());
- return out;
- }
- virtual unsigned count() override { return parent->getAttributeCount(); }
- };
- class CSortedAttributeIterator : implements IAttributeIterator, public CInterface
- {
- typedef ArrayIteratorOf<AttrArray, AttrValue &> AttrIterator;
- AttrArray attrs;
- AttrValue *cur;
- AttrIterator *iter;
- Linked<const PTree> parent;
- public:
- IMPLEMENT_IINTERFACE;
- static int compareAttrs(AttrValue * const *ll, AttrValue * const *rr)
- {
- return stricmp((*ll)->key.get(), (*rr)->key.get());
- };
- CSortedAttributeIterator(const PTree *_parent) : cur(NULL), iter(NULL), parent(_parent)
- {
- AttrValue *cur = parent->getNextAttribute(nullptr);
- if (cur)
- {
- do
- {
- attrs.append(*cur);
- cur = parent->getNextAttribute(cur);
- }
- while (cur);
- attrs.sort(compareAttrs);
- iter = new AttrIterator(attrs);
- }
- }
- ~CSortedAttributeIterator()
- {
- if (iter)
- delete iter;
- }
- // IAttributeIterator impl.
- virtual bool first() override
- {
- if (!iter) return false;
- if (!iter->first()) { cur = NULL; return false; }
- cur = &iter->query();
- return true;
- }
- virtual bool next() override
- {
- if (!iter) return false;
- if (!iter->next()) { cur = NULL; return false; }
- cur = &iter->query();
- return true;
- }
- virtual bool isValid() override { return cur!=NULL; }
- virtual const char *queryName() const override
- {
- assertex(cur);
- return cur->key.get();
- }
- virtual const char *queryValue() const override
- {
- assertex(cur);
- return cur->value.get();
- }
- virtual StringBuffer &getValue(StringBuffer &out) override
- {
- assertex(cur);
- return out.append(queryValue());
- }
- virtual unsigned count() override { return attrs.ordinality(); }
- };
- if (sorted)
- return new CSortedAttributeIterator(this);
- else
- return new CAttributeIterator(this);
- }
- ///////////////////
- class CIndexIterator : implements IPropertyTreeIterator, public CInterface
- {
- Owned<IPropertyTreeIterator> subIter;
- IPropertyTree *celem;
- unsigned index, current;
- public:
- IMPLEMENT_IINTERFACE;
- CIndexIterator(IPropertyTreeIterator *_subIter, unsigned _index) : subIter(_subIter), index(_index)
- {
- }
- // IPropertyTreeIterator
- virtual bool first() override
- {
- if (!index)
- return false;
- if (!subIter->first())
- return false;
- current = 1;
- celem = NULL;
- do
- {
- if (current == index)
- {
- celem = &subIter->query();
- return true;
- }
- if (!subIter->next())
- return false;
- } while (++current <= index);
- return false;
- }
- virtual bool isValid() override
- {
- return celem && (index >= current);
- }
- virtual bool next() override
- {
- celem = NULL;
- return false;
- }
- virtual IPropertyTree & query() override
- {
- return *celem;
- }
- };
- IPropertyTreeIterator *PTree::getElements(const char *xpath, IPTIteratorCodes flags) const
- {
- // NULL iterator for local value (i.e. maybe be single value or array)
- if (NULL == xpath || '\0' == *xpath)
- return new SingleIdIterator(*this);
- Owned<IPropertyTreeIterator> iter;
- const char *_xpath = xpath;
- bool root=true;
- restart:
- switch (*xpath)
- {
- case '.':
- root=false;
- ++xpath;
- if ('\0' == *xpath)
- return new SingleIdIterator(*this);
- else if ('/' != *xpath)
- throw MakeXPathException(xpath-1, PTreeExcpt_XPath_Unsupported, 0, "\"/\" expected");
- goto restart;
- case '/':
- ++xpath;
- if ('/' == *xpath)
- {
- iter.setown(getElements(xpath+1));
- if (checkChildren())
- {
- IPropertyTreeIterator *iter2 = new PTIdMatchIterator(this, "*", isnocase(), flags & iptiter_sort);
- iter2 = new PTStackIterator(iter2, xpath-1);
- SeriesPTIterator *series = new SeriesPTIterator();
- series->addIterator(iter.getClear());
- series->addIterator(iter2);
- return series;
- }
- else
- return iter.getClear();
- }
- else if (root)
- throw MakeXPathException(xpath, PTreeExcpt_XPath_Unsupported, 0, "Root specifier \"/\" specifier is not supported");
- else if ('\0' == *xpath)
- return new SingleIdIterator(*this);
- goto restart;
- case '[':
- {
- ++xpath;
- if (isdigit(*xpath)) {
- StringAttr index;
- xpath = readIndex(xpath, index);
- unsigned i = atoi(index.get());
- if (i)
- {
- if (value && value->isArray())
- {
- IPropertyTree *element = value->queryElement(--i);
- if (element)
- {
- iter.setown(element->getElements(NULL));
- }
- }
- else if (i == 1)
- iter.setown(new SingleIdIterator(*this));
- }
- }
- else
- {
- if (checkPattern(xpath))
- iter.setown(new SingleIdIterator(*this));
- }
- if (']' != *xpath)
- throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
- ++xpath;
- break;
- }
- default:
- {
- bool wild;
- const char *start = xpath;
- readWildId(xpath, wild);
- size32_t s = xpath-start;
- if (s)
- {
- MAKE_LSTRING(id, start, s);
- if (checkChildren())
- {
- IPropertyTree *child = NULL;
- if (!wild)
- child = children->query(id);
- if ((wild || child) && '[' == *xpath) // check for local index not iterative qualifier.
- {
- const char *xxpath = xpath+1;
- if (isdigit(*xxpath)) {
- StringAttr idxstr;
- xxpath = readIndex(xxpath, idxstr);
- if (']' != *xxpath)
- throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
- ++xxpath;
- unsigned index = atoi(idxstr.get());
- if (index)
- {
- Owned<IPropertyTreeIterator> _iter = getElements(id);
- if (_iter->first())
- {
- do
- {
- if (0 == --index)
- {
- iter.setown(new SingleIdIterator((PTree &)_iter->query()));
- break;
- }
- }
- while (_iter->next());
- }
- }
- xpath = xxpath;
- }
- else
- {
- if (wild)
- iter.setown(new PTIdMatchIterator(this, id, isnocase(), flags & iptiter_sort));
- else
- iter.setown(child->getElements(NULL));
- const char *start = xxpath-1;
- for (;;)
- {
- char quote = 0;
- while (']' != *(++xxpath) || quote)
- {
- switch (*xxpath) {
- case '\"':
- case '\'':
- {
- if (quote)
- {
- if (*xxpath == quote)
- quote = 0;
- }
- else
- quote = *xxpath;
- break;
- }
- case '\0':
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xxpath-start, "Qualifier brace unclosed");
- }
- }
- ++xxpath;
- if ('[' == *xxpath)
- {
- ++xxpath;
- if (isdigit(*xxpath))
- {
- StringAttr qualifier(start, (xxpath-1)-start);
- Owned<PTStackIterator> siter = new PTStackIterator(iter.getClear(), qualifier.get());
- StringAttr index;
- xxpath = readIndex(xxpath, index);
- unsigned i = atoi(index.get());
- iter.setown(new CIndexIterator(siter.getClear(), i));
- ++xxpath;
- break;
- }
- }
- else
- {
- StringAttr qualifier(start, xxpath-start);
- iter.setown(new PTStackIterator(iter.getClear(), qualifier.get()));
- break;
- }
- }
- xpath = xxpath;
- }
- }
- else
- {
- if (wild)
- iter.setown(new PTIdMatchIterator(this, id, isnocase(), flags & iptiter_sort));
- else if (child)
- iter.setown(child->getElements(NULL));
- }
- }
- }
- break;
- }
- }
- if (!iter)
- iter.setown(LINK(nullPTreeIterator));
- if (*xpath == '\0' || (*xpath == '/' && '\0' == *(xpath+1)))
- return iter.getClear();
- else
- return new PTStackIterator(iter.getClear(), xpath);
- }
- void PTree::localizeElements(const char *xpath, bool allTail)
- {
- // null action for local ptree
- }
- unsigned PTree::numChildren()
- {
- if (!checkChildren()) return 0;
- return children->numChildren();
- }
- unsigned PTree::getCount(const char *xpath)
- {
- unsigned c=0;
- Owned<IPropertyTreeIterator> iter = getElements(xpath);
- ForEach(*iter)
- ++c;
- return c;
- }
- void getXPathMatchTree(IPropertyTree &parentContext, const char *xpath, IPropertyTree *&matchContainer)
- {
- if (!xpath || !*xpath)
- {
- matchContainer = createPTree(parentContext.queryName());
- return;
- }
- StringBuffer head;
- const char *str = xpath;
- const char *end = str+strlen(xpath);
- bool quote = false;
- bool inQualifier = false;
- bool done = false;
- bool recurse = false;
- while (end != str)
- {
- switch (*str) {
- case '"':
- if (quote) quote = false;
- else quote = true;
- break;
- case '[':
- if (inQualifier)
- {
- if (!quote)
- throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, str-xpath, "Unclosed qualifier detected");
- }
- else
- inQualifier = true;
- break;
- case ']':
- if (inQualifier)
- {
- if (!quote)
- inQualifier = false;
- }
- else if (!quote)
- throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, str-xpath, "Unopened qualifier detected");
- break;
- case '/':
- if (!quote && !inQualifier)
- {
- if ('/' == *(str+1))
- recurse = true;
- done = true;
- }
- break;
- }
- if (done) break;
- ++str;
- }
- const char *tail;
- if (str==end) // top-level matches
- {
- head.append(xpath);
- if (0 == head.length())
- {
- matchContainer = createPTree(xpath);
- return;
- }
- tail = NULL;
- }
- else
- {
- head.append(str-xpath, xpath);
- if (recurse)
- tail = str+2;
- else
- tail = str+1;
- }
- Owned<IPropertyTreeIterator> parentIter = parentContext.getElements(head.str());
- Owned<IPropertyTree> matchParent;
- ForEach (*parentIter)
- {
- IPropertyTree &parent = parentIter->query();
- if (!matchParent)
- matchParent.setown(createPTree(parentContext.queryName()));
- if (tail && *tail)
- {
- IPropertyTree *childContainer = NULL;
- getXPathMatchTree(parent, tail, childContainer);
- if (childContainer)
- {
- if (!head.length())
- matchParent.setown(childContainer);
- else
- {
- unsigned pos = ((PTree &)parentContext).findChild(&parent);
- matchParent->addPropTree(childContainer->queryName(), childContainer);
- childContainer->setPropInt("@pos", pos+1);
- }
- if (!matchContainer)
- matchContainer = LINK(matchParent);
- }
- if (recurse)
- {
- Owned<IPropertyTreeIterator> iter = parent.getElements("*");
- ForEach (*iter)
- {
- IPropertyTree *childContainer = NULL;
- IPropertyTree &child = iter->query();
- getXPathMatchTree(child, xpath, childContainer);
- if (childContainer)
- {
- unsigned pos = ((PTree &)parent).findChild(&child);
- matchParent->addPropTree(childContainer->queryName(), childContainer);
- childContainer->setPropInt("@pos", pos+1);
- if (!matchContainer)
- matchContainer = LINK(matchParent);
- }
- }
- }
- }
- else
- {
- if (&parent != &parentContext)
- {
- IPropertyTree *childContainer = matchParent->addPropTree(parent.queryName(), createPTree());
- unsigned pos = ((PTree &)parentContext).findChild(&parent);
- childContainer->setPropInt("@pos", pos+1);
- }
- if (!matchContainer)
- matchContainer = LINK(matchParent);
- }
- }
- }
- IPropertyTree *getXPathMatchTree(IPropertyTree &parent, const char *xpath)
- {
- IPropertyTree *matchTree = NULL;
- getXPathMatchTree(parent, xpath, matchTree);
- return matchTree;
- }
- void PTree::serializeAttributes(MemoryBuffer &tgt)
- {
- IAttributeIterator *aIter = getAttributes();
- if (aIter->first())
- {
- do
- {
- tgt.append(aIter->queryName());
- tgt.append(aIter->queryValue());
- }
- while (aIter->next());
- }
- tgt.append(""); // attribute terminator. i.e. blank attr name.
- aIter->Release();
- }
- void PTree::serializeSelf(MemoryBuffer &tgt)
- {
- const char *_name = queryName();
- tgt.append(_name ? _name : "");
- tgt.append(flags);
- serializeAttributes(tgt);
- if (value)
- value->serialize(tgt);
- else
- tgt.append((size32_t)0);
- }
- void PTree::serializeCutOff(MemoryBuffer &tgt, int cutoff, int depth)
- {
- serializeSelf(tgt);
- if (-1 == cutoff || depth<cutoff)
- {
- Owned<IPropertyTreeIterator> iter = getElements("*");
- if (iter->first())
- {
- do
- {
- IPropertyTree *_child = &iter->query();
- PTree *child = QUERYINTERFACE(_child, PTree); assertex(child);
- child->serializeCutOff(tgt, cutoff, depth+1);
- }
- while (iter->next());
- }
- }
- tgt.append(""); // element terminator. i.e. blank child name.
- }
- // serializable impl.
- void PTree::serialize(MemoryBuffer &tgt)
- {
- serializeCutOff(tgt, -1, 0);
- }
- void PTree::deserialize(MemoryBuffer &src)
- {
- deserializeSelf(src);
- StringAttr eName;
- for (;;)
- {
- size32_t pos = src.getPos();
- src.read(eName);
- if (eName.isEmpty())
- break;
- src.reset(pos); // reset to re-read tree name
- IPropertyTree *child = create(src);
- addPropTree(eName, child);
- }
- }
- void PTree::deserializeSelf(MemoryBuffer &src)
- {
- setName(NULL); // needs to be cleared before flags changed
- StringAttr _name;
- src.read(_name);
- src.read(flags);
- if (_name[0]==0)
- setName(NULL);
- else
- setName(_name);
- StringAttr attrName, attrValue;
- for (;;)
- {
- src.read(attrName);
- if (attrName.isEmpty())
- break;
- src.read(attrValue);
- setProp(attrName, attrValue);
- }
- size32_t size;
- unsigned pos = src.getPos();
- src.read(size);
- if (value) delete value;
- if (size)
- {
- src.reset(pos);
- value = new CPTValue(src);
- }
- else value = NULL;
- }
- IPropertyTree *PTree::clone(IPropertyTree &srcTree, bool self, bool sub)
- {
- IPropertyTree *_dstTree = self ? this : create(srcTree.queryName());
- PTree *dstTree = QUERYINTERFACE(_dstTree, PTree);
- dbgassertex(dstTree);
- if (self)
- dstTree->setName(srcTree.queryName());
- clone(srcTree, *dstTree, sub);
- return _dstTree;
- }
- void PTree::clone(IPropertyTree &srcTree, IPropertyTree &dstTree, bool sub)
- {
- PTree *_dstTree = QUERYINTERFACE((&dstTree), PTree); assertex(_dstTree); //JCSMORE
- flags = _dstTree->flags;
- if (srcTree.isBinary(NULL))
- {
- MemoryBuffer mb;
- verifyex(srcTree.getPropBin(NULL, mb));
- dstTree.setPropBin(NULL, mb.length(), mb.toByteArray());
- }
- else if (srcTree.isCompressed(NULL))
- {
- StringBuffer s;
- verifyex(srcTree.getProp(NULL, s));
- dstTree.setProp(NULL, s.str());
- }
- else
- dstTree.setProp(NULL, srcTree.queryProp(NULL));
- IAttributeIterator *attrs = srcTree.getAttributes();
- if (attrs->first())
- {
- do
- {
- dstTree.setProp(attrs->queryName(), attrs->queryValue());
- }
- while (attrs->next());
- }
- attrs->Release();
- if (sub)
- {
- Owned<IPropertyTreeIterator> iter = srcTree.getElements("*");
- if (iter->first())
- {
- do
- {
- IPropertyTree &child = iter->query();
- IPropertyTree *newChild = clone(child, false, sub);
- dstTree.addPropTree(newChild->queryName(), newChild);
- }
- while (iter->next());
- }
- }
- }
- IPropertyTree *PTree::ownPTree(IPropertyTree *tree)
- {
- if (!isEquivalent(tree) || tree->IsShared() || isCaseInsensitive() != tree->isCaseInsensitive())
- {
- IPropertyTree *newTree = clone(*tree);
- tree->Release();
- return newTree;
- }
- else
- return tree;
- }
- IPropertyTree *PTree::queryCreateBranch(IPropertyTree *branch, const char *prop, bool *newBranch)
- {
- IPropertyTree *childBranch = branch->queryPropTree(prop);
- if (!childBranch)
- {
- if (newBranch) *newBranch = true;
- childBranch = create(prop);
- branch->setPropTree(prop, childBranch);
- }
- else if (newBranch) *newBranch = false;
- return childBranch;
- }
- IPropertyTree *PTree::splitBranchProp(const char *xpath, const char *&prop, bool error)
- {
- prop = splitXPathX(xpath);
- MAKE_LSTRING(path, xpath, prop-xpath);
- IPropertyTree *branch = queryPropTree(path);
- if (!branch && error)
- throw MakeIPTException(-1, "path %s not found, when setting prop %s", path, xpath);
- return branch;
- }
- IPropertyTree *_createPropBranch(IPropertyTree *tree, const char *xpath, bool createIntermediates, IPropertyTree *&created, IPropertyTree *&createdParent)
- {
- const char *prop;
- StringBuffer path;
- prop = splitXPathUQ(xpath, path);
- IPropertyTree *branch = tree->queryPropTree(path.str());
- if (!branch)
- {
- if (path.length() == strlen(xpath))
- throw MakeIPTException(-1, "createPropBranch: cannot create path : %s", xpath);
- if (!createIntermediates)
- throw MakeIPTException(-1, "createPropBranch: no path found for : %s", path.str());
-
- if ('/' == path.charAt(path.length()-1))
- path.remove(path.length()-1, 1);
- branch = _createPropBranch(tree, path.str(), createIntermediates, created, createdParent);
- assertex(branch);
- }
- if (prop && '\0' != *prop && '@' != *prop)
- {
- IPropertyTree *_branch = branch->queryPropTree(prop);
- if (_branch)
- branch = _branch;
- else
- {
- IPropertyTree *p = branch;
- branch = branch->addPropTree(prop, createPTree());
- if (!created) { created = branch; createdParent = p; }
- }
- }
- return branch;
- }
- IPropertyTree *createPropBranch(IPropertyTree *tree, const char *xpath, bool createIntermediates, IPropertyTree **created, IPropertyTree **createdParent)
- {
- IPropertyTree *_created = NULL, *_createdParent = NULL;
- try
- {
- IPropertyTree *ret = _createPropBranch(tree, xpath, createIntermediates, _created, _createdParent);
- if (created) *created = _created;
- if (createdParent) *createdParent = _createdParent;
- return ret;
- }
- catch (...)
- {
- if (_created) (_createdParent)->removeTree(_created);
- throw;
- }
- }
- void PTree::addLocal(size32_t l, const void *data, bool _binary, int pos)
- {
- if (!l) return; // right thing to do on addProp("x", NULL) ?
- IPTArrayValue *newValue = new CPTValue(l, data, _binary);
- Owned<IPropertyTree> tree = create(queryName(), newValue);
- PTree *_tree = QUERYINTERFACE(tree.get(), PTree); assertex(_tree); _tree->setParent(this);
- addingNewElement(*tree, pos);
- IPTArrayValue *array;
- if (value && value->isArray())
- {
- array = value;
- if (pos != -1 && ((unsigned)pos > array->elements()))
- throw MakeIPTException(-1, "Error trying to insert element at %d of %d", pos, array->elements());
- }
- else
- {
- if (pos > 0)
- throw MakeIPTException(-1, "Error trying to insert element at %d of 0", pos);
- // detach children and attributes of this branch now owned by element of newly created array.
- IPropertyTree *element1 = detach();
- array = new CPTArray();
- addingNewElement(*element1, ANE_APPEND);
- array->addElement(element1);
- value = array;
- }
- tree->Link();
- if (-1 == pos)
- array->addElement(tree);
- else
- array->setElement(pos, tree);
- if (_binary)
- IptFlagSet(flags, ipt_binary);
- else
- IptFlagClr(flags, ipt_binary);
- }
- enum exprType { t_none, t_equality, t_inequality, t_lteq, t_lt, t_gt, t_gteq } tType;
- inline bool match(bool wild, bool numeric, const char *xpath, exprType t, const char *value, unsigned len, const char *pat, unsigned patLen, bool nocase)
- {
- int m;
- if (numeric)
- {
- __int64 lhsN = atoi64_l(value, len);
- __int64 rhsN = atoi64_l(pat, patLen);
- m = lhsN<rhsN?-1:lhsN>rhsN?1:0;
- }
- else if (wild)
- m = false==WildMatch(value, len, pat, patLen, nocase);
- else
- {
- if (len == patLen)
- m = nocase ? memicmp(value, pat, len) : memcmp(value, pat, len);
- else if (len < patLen)
- m = -1;
- else
- m = 1;
- }
- switch (t)
- {
- case t_inequality:
- return m!=0;
- case t_lt:
- return m<0;
- case t_lteq:
- return m<=0;
- case t_equality:
- return m==0;
- case t_gteq:
- return m>=0;
- case t_gt:
- return m>0;
- }
- throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Invalid xpath qualifier expression in xpath: %s", xpath);
- }
- bool PTree::checkPattern(const char *&xxpath) const
- {
- // Pattern is an additional filter at the current node level
- // It can be [condition], or it can be empty (we don't support anything else)
- // supported conditions are:
- // tag - must have child called tag
- // @attr - must have attribute called attr
- // tag="value" - must have child called tag with given value
- // @attr="value" - must have attribute called attr with given value
- const char *xpath = xxpath;
- while (*xpath == ' ' || *xpath == '\t') xpath++;
- const char *start = xpath;
- bool wild = false, nocase = isnocase();
- if (*xpath=='@')
- xpath++;
- char quote = 0;
- const char *lhsEnd, *quoteBegin, *quoteEnd, *rhsBegin, *rhsEnd;
- lhsEnd = quoteBegin = quoteEnd = rhsBegin = rhsEnd = NULL;
- exprType tType = t_none;
- bool numeric=false;
- #ifdef WARNLEGACYCOMPARE
- bool legacynumeric=false;
- #endif
- for (;;)
- {
- switch (*xpath) {
- case '"':
- case '\'':
- if (quote)
- {
- if (*xpath == quote)
- {
- quote = 0;
- quoteEnd = xpath;
- }
- }
- else
- {
- if (quoteBegin)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Quoted left hand side already seen");
- quote = *xpath;
- quoteBegin = xpath+1;
- }
- break;
- case '[':
- if (!quote)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unclosed qualifier detected");
- break;
- case ']':
- if (!quote)
- {
- if (!lhsEnd)
- lhsEnd = xpath;
- rhsEnd = xpath;
- }
- break;
- case ' ':
- case '\t':
- if (!lhsEnd)
- lhsEnd = xpath;
- break;
- case '!':
- if (!quote)
- {
- if (tType)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator xpath");
- if ('=' != *(xpath+1))
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Invalid xpath qualifier expression in xpath");
- if (!lhsEnd)
- lhsEnd = xpath;
- ++xpath;
- tType = t_inequality;
- wild = true; // true by default now, introduced ~ syntax, to denote wild string
- }
- break;
- case '=':
- if (!quote)
- {
- if (wild)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Wildcard match '~' makes no sense in this context");
- if (tType)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator xpath");
- tType = t_equality;
- wild = true; // true by default now, introduced ~ syntax, to denote wild string
- if (!lhsEnd)
- lhsEnd = xpath;
- }
- break;
- case '>':
- if (!quote)
- {
- if (wild)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Wildcard match '~' makes no sense in this context");
- if (tType)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator in xpath");
- if (!lhsEnd)
- lhsEnd = xpath;
- #ifdef WARNLEGACYCOMPARE
- legacynumeric = true;
- #endif
- if ('=' == *(xpath+1))
- {
- ++xpath;
- tType = t_gteq;
- }
- else
- tType = t_gt;
- }
- break;
- case '<':
- if (!quote)
- {
- if (tType)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected expression operator in xpath");
- if (!lhsEnd)
- lhsEnd = xpath;
- #ifdef WARNLEGACYCOMPARE
- legacynumeric = true;
- #endif
- if ('=' == *(xpath+1))
- {
- ++xpath;
- tType = t_lteq;
- }
- else
- tType = t_lt;
- }
- break;
- case '~':
- if (!quote)
- {
- if (!tType)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected wild operator in xpath");
- wild = true;
- }
- break;
- case '?':
- if (!quote)
- {
- if (!tType)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Unexpected case-insensitive operator in xpath");
- nocase = true;
- }
- break;
- case '\0':
- rhsEnd = xpath;
- break;
- }
- if (rhsEnd)
- break;
- xpath++;
- if (!rhsBegin && tType && !isspace(*xpath))
- rhsBegin = xpath;
- }
- if (quote)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, unclosed quoted content");
- if (tType)
- {
- if (quoteBegin && !quoteEnd)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, RHS missing closing quote");
- if (rhsBegin && !rhsEnd)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, RHS missing closing quote");
- if (!quoteBegin && rhsEnd) // validate it's a numeric
- {
- const char *c = rhsBegin;
- for (;;)
- {
- if (!isdigit(*c++))
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Parse error, RHS is an unquoted string");
- if (c==rhsEnd) break;
- }
- }
- }
- MAKE_LSTRING(lhs, start, lhsEnd-start);
- bool ret = false;
- const char *tProp = splitXPathX(lhs);
- MAKE_LSTRING(head, lhs, tProp-lhs);
- Owned<IPropertyTreeIterator> iter = getElements(head);
- ForEach (*iter)
- {
- IPropertyTree &found = iter->query();
- if (t_none == tType)
- {
- if (found.hasProp(tProp))
- {
- ret = true;
- break;
- }
- }
- else
- {
- Owned<IPropertyTreeIterator> _iter2;
- IPropertyTreeIterator *iter2;
- IPropertyTree *matchElem;
- if (isAttribute(tProp))
- {
- matchElem = &found;
- iter2 = NULL;
- }
- else
- {
- _iter2.setown(found.getElements(tProp));
- iter2 = _iter2;
- if (iter2->first())
- matchElem = &iter2->query();
- else
- continue;
- tProp = NULL;
- }
- for (;;)
- {
- if (matchElem->isBinary(tProp))
- UNIMPLEMENTED;
- const char *rhs;
- unsigned rhslength;
- if (quoteEnd)
- {
- rhs = quoteBegin;
- rhslength = quoteEnd-quoteBegin;
- #ifdef WARNLEGACYCOMPARE
- if (legacynumeric)
- {
- if (isdigit(*rhs))
- WARNLOG("Possible deprecated use of quoted numeric comparison operation: %s", xxpath);
- }
- #endif
- }
- else if (rhsEnd)
- {
- rhs = rhsBegin;
- rhslength = rhsEnd-rhsBegin;
- numeric = true;
- }
- else
- {
- rhs = NULL;
- rhslength = 0;
- }
- if (matchElem->isCompressed(tProp))
- {
- StringBuffer s;
- matchElem->getProp(tProp, s);
- ret = match(wild, numeric, xxpath, tType, s.str(), s.length(), rhs, rhslength, nocase);
- }
- else
- {
- const char *value = matchElem->queryProp(tProp);
- if (value)
- ret = match(wild, numeric, xxpath, tType, value, value?(size32_t)strlen(value):0, rhs, rhslength, nocase);
- else if (tType == t_equality)
- ret = (NULL == rhs || '\0' == *rhs);
- else if (tType == t_inequality)
- ret = (NULL != rhs && '\0' != *rhs);
- }
- if (ret)
- break;
- if (!iter2 || !iter2->next())
- break;
- matchElem = &iter2->query();
- }
- if (ret)
- break;
- }
- }
- xxpath = xpath;
- return ret;
- }
- AttrValue *PTree::findAttribute(const char *key) const
- {
- AttrValue *a = attrs+numAttrs;
- if (isnocase())
- {
- while (a-- != attrs)
- {
- if (strieq(a->key.get(), key))
- return a;
- }
- }
- else
- {
- while (a-- != attrs)
- {
- if (streq(a->key.get(), key))
- return a;
- }
- }
- return nullptr;
- }
- const char *PTree::getAttributeValue(const char *key) const
- {
- AttrValue *e = findAttribute(key);
- if (e)
- return e->value.get();
- return nullptr;
- }
- unsigned PTree::getAttributeCount() const
- {
- return numAttrs;
- }
- AttrValue *PTree::getNextAttribute(AttrValue *cur) const
- {
- if (0 == numAttrs)
- return nullptr;
- else if (nullptr == cur)
- return attrs;
- else
- {
- if (cur == (attrs+(numAttrs-1)))
- return nullptr;
- return ++cur;
- }
- }
- //////////////////////
- // LocalPTree
- LocalPTree::LocalPTree(const char *_name, byte _flags, IPTArrayValue *_value, ChildMap *_children) : PTree(_flags, _value, _children)
- {
- if (_name)
- setName(_name);
- }
- LocalPTree::~LocalPTree()
- {
- name.destroy();
- if (!attrs)
- return;
- AttrValue *a = attrs+numAttrs;
- while (a--!=attrs)
- {
- a->key.destroy();
- a->value.destroy();
- }
- free(attrs);
- }
- const char *LocalPTree::queryName() const
- {
- return name.get();
- }
- void LocalPTree::setName(const char *_name)
- {
- if (_name==name.get())
- return;
- AttrStr *oname = name.getPtr(); // Don't free until after we copy - they could overlap
- if (!name.set(_name))
- name.setPtr(AttrStr::create(_name));
- if (oname)
- AttrStr::destroy(oname);
- }
- bool LocalPTree::removeAttribute(const char *key)
- {
- AttrValue *del = findAttribute(key);
- if (!del)
- return false;
- numAttrs--;
- unsigned pos = del-attrs;
- del->key.destroy();
- del->value.destroy();
- memmove(attrs+pos, attrs+pos+1, (numAttrs-pos)*sizeof(AttrValue));
- return true;
- }
- void LocalPTree::setAttribute(const char *key, const char *val)
- {
- if (!key)
- return;
- if (!validateXMLTag(key+1))
- throw MakeIPTException(-1, "Invalid xml attribute: %s", key);
- if (!val)
- val = ""; // cannot have NULL value
- AttrValue *v = findAttribute(key);
- AttrStr *goer = nullptr;
- if (v)
- {
- if (streq(v->value.get(), val))
- return;
- goer = v->value.getPtr();
- }
- else
- {
- attrs = (AttrValue *)realloc(attrs, (numAttrs+1)*sizeof(AttrValue));
- v = &attrs[numAttrs++];
- if (!v->key.set(key))
- v->key.setPtr(isnocase() ? AttrStr::createNC(key) : AttrStr::create(key));
- }
- if (!v->value.set(val))
- v->value.setPtr(AttrStr::create(val));
- if (goer)
- AttrStr::destroy(goer);
- }
- #ifdef TRACE_STRING_SIZE
- std::atomic<__int64> AttrStr::totsize { 0 };
- std::atomic<__int64> AttrStr::maxsize { 0 };
- #endif
- #ifdef TRACE_ATOM_SIZE
- std::atomic<__int64> AttrStrAtom::totsize { 0 };
- std::atomic<__int64> AttrStrAtom::maxsize { 0 };
- #endif
- ///////////////////
- CAtomPTree::CAtomPTree(const char *_name, byte _flags, IPTArrayValue *_value, ChildMap *_children) : PTree(_flags, _value, _children)
- {
- if (_name)
- setName(_name);
- }
- CAtomPTree::~CAtomPTree()
- {
- bool nc = isnocase();
- HashKeyElement *name_ptr = name.getPtr();
- if (name_ptr)
- {
- AtomRefTable *kT = nc?keyTableNC:keyTable;
- #ifdef TRACE_ATOM_SIZE
- size_t gosize = sizeof(HashKeyElement)+strlen(name_ptr->get())+1;
- if (kT->releaseKey(name_ptr))
- AttrStrAtom::totsize -= gosize;
- #else
- kT->releaseKey(name_ptr);
- #endif
- }
- if (!attrs)
- return;
- AttrValue *a = attrs+numAttrs;
- {
- CriticalBlock block(hashcrit);
- while (a--!=attrs)
- {
- if (a->key.isPtr())
- attrHT->removekey(a->key.getPtr(), nc);
- if (a->value.isPtr())
- attrHT->removeval(a->value.getPtr());
- }
- freeAttrArray(attrs, numAttrs);
- }
- }
- void CAtomPTree::setName(const char *_name)
- {
- AtomRefTable *kT = isnocase()?keyTableNC:keyTable;
- HashKeyElement *oname = name.getPtr(); // NOTE - don't release yet as could overlap source name
- if (!_name)
- name.setPtr(nullptr);
- else
- {
- if (!validateXMLTag(_name))
- throw MakeIPTException(PTreeExcpt_InvalidTagName, ": %s", _name);
- if (!name.set(_name))
- {
- #ifdef TRACE_ALL_ATOM
- DBGLOG("TRACE_ALL_ATOM: %s", _name);
- #endif
- #ifdef TRACE_ATOM_SIZE
- bool didCreate;
- name.setPtr(kT->queryCreate(_name, didCreate));
- if (didCreate)
- {
- AttrStrAtom::totsize += sizeof(HashKeyElement)+strlen(_name)+1;
- if (AttrStrAtom::totsize > AttrStrAtom::maxsize)
- {
- AttrStrAtom::maxsize.store(AttrStrAtom::totsize);
- DBGLOG("TRACE_ATOM_SIZE: total size now %" I64F "d", AttrStrAtom::maxsize.load());
- }
- }
- #else
- name.setPtr(kT->queryCreate(_name));
- #endif
- }
- }
- if (oname)
- {
- #ifdef TRACE_ATOM_SIZE
- size_t gosize = sizeof(HashKeyElement)+strlen(oname->get())+1;
- if (kT->releaseKey(oname))
- AttrStrAtom::totsize -= gosize;
- #else
- kT->releaseKey(oname);
- #endif
- }
- }
- const char *CAtomPTree::queryName() const
- {
- return name.get();
- }
- unsigned CAtomPTree::queryHash() const
- {
- if (name.isPtr())
- {
- assert(name.getPtr());
- return name.getPtr()->queryHash();
- }
- else
- {
- const char *_name = name.get();
- size32_t nl = strlen(_name);
- return isnocase() ? hashnc((const byte *) _name, nl, 0): hashc((const byte *) _name, nl, 0);
- }
- }
- AttrValue *CAtomPTree::newAttrArray(unsigned n)
- {
- // NB crit must be locked
- if (!n)
- return nullptr;
- if (freelistmax<=n)
- {
- freelist = (AttrValue **)realloc(freelist, sizeof(AttrValue *)*(n+1));
- while (freelistmax<=n)
- freelist[freelistmax++] = nullptr;
- }
- AttrValue *&p = freelist[n];
- AttrValue *ret = p;
- if (ret)
- p = *(AttrValue **)ret;
- else
- ret = (AttrValue *)freeallocator.alloc(sizeof(AttrValue)*n);
- return ret;
- }
- void CAtomPTree::freeAttrArray(AttrValue *a, unsigned n)
- {
- // NB crit must be locked
- if (a)
- {
- AttrValue *&p = freelist[n];
- *(AttrValue **)a = p;
- p = a;
- }
- }
- void CAtomPTree::setAttribute(const char *key, const char *val)
- {
- if (!key)
- return;
- if (!validateXMLTag(key+1))
- throw MakeIPTException(-1, "Invalid xml attribute: %s", key);
- if (!val)
- val = ""; // cannot have NULL value
- AttrValue *v = findAttribute(key);
- if (v)
- {
- if (streq(v->value.get(), val))
- return;
- CriticalBlock block(hashcrit);
- if (v->value.isPtr())
- attrHT->removeval(v->value.getPtr());
- if (!v->value.set(val))
- v->value.setPtr(attrHT->addval(val));
- }
- else
- {
- CriticalBlock block(hashcrit);
- AttrValue *newattrs = newAttrArray(numAttrs+1);
- memcpy(newattrs, attrs, numAttrs*sizeof(AttrValue));
- v = &newattrs[numAttrs];
- if (!v->key.set(key))
- v->key.setPtr(attrHT->addkey(key, isnocase()));
- if (!v->value.set(val))
- v->value.setPtr(attrHT->addval(val));
- freeAttrArray(attrs, numAttrs);
- numAttrs++;
- attrs = newattrs;
- }
- }
- bool CAtomPTree::removeAttribute(const char *key)
- {
- AttrValue *del = findAttribute(key);
- if (!del)
- return false;
- numAttrs--;
- CriticalBlock block(hashcrit);
- if (del->key.isPtr())
- attrHT->removekey(del->key.getPtr(), isnocase());
- if (del->value.isPtr())
- attrHT->removeval(del->value.getPtr());
- AttrValue *newattrs = newAttrArray(numAttrs);
- if (newattrs)
- {
- unsigned pos = del-attrs;
- memcpy(newattrs, attrs, pos*sizeof(AttrValue));
- memcpy(newattrs+pos, attrs+pos+1, (numAttrs-pos)*sizeof(AttrValue));
- }
- freeAttrArray(attrs, numAttrs+1);
- attrs = newattrs;
- return true;
- }
- ///////////////////
- bool isEmptyPTree(IPropertyTree *t)
- {
- if (!t)
- return true;
- if (t->numUniq())
- return false;
- Owned<IAttributeIterator> ai = t->getAttributes();
- if (ai->first())
- return false;
- const char *s = t->queryProp(NULL);
- if (s&&*s)
- return false;
- return true;
- }
- ///////////////////
- PTLocalIteratorBase::PTLocalIteratorBase(const PTree *_tree, const char *_id, bool _nocase, bool _sort) : nocase(_nocase), sort(_sort), id(_id), tree(_tree)
- {
- class CPTArrayIterator : public ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>
- {
- public:
- CPTArrayIterator(IPropertyTreeIterator &src) : ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>(elems)
- {
- ForEach(src)
- elems.append(src.get());
- elems.sort(comparePropTrees);
- }
- IArrayOf<IPropertyTree> elems;
- };
- tree->Link();
- baseIter = tree->checkChildren()->getIterator(sort);
- iter = NULL;
- current = NULL;
- }
- PTLocalIteratorBase::~PTLocalIteratorBase()
- {
- baseIter->Release();
- ::Release(iter);
- tree->Release();
- }
- // IPropertyTreeIterator
- bool PTLocalIteratorBase::first()
- {
- ::Release(iter); iter=NULL;
- if (!baseIter || !baseIter->first()) return false;
- return _next();
- }
- bool PTLocalIteratorBase::_next()
- {
- if (iter && iter->isValid() && iter->next())
- return true;
- for (;;)
- {
- for (;;)
- {
- if (!baseIter->isValid())
- {
- current = NULL;
- return false;
- }
- else if (match())
- break;
- baseIter->next();
- }
- IPropertyTree *element = &baseIter->query();
- baseIter->next();
- if (iter)
- iter->Release();
- iter = element->getElements(NULL);
- if (iter->first())
- {
- current = &iter->query();
- return true;
- }
- }
- }
- bool PTLocalIteratorBase::next()
- {
- return _next();
- }
- bool PTLocalIteratorBase::isValid()
- {
- return (current != NULL);
- }
- /////////////////////////////
- bool PTIdMatchIterator::match()
- {
- IPropertyTree &tree = baseIter->query();
- const char *key = tree.queryName();
- return (0 != WildMatch(key, id, nocase));
- }
- ////////////////////////////
- SingleIdIterator::SingleIdIterator(const PTree &_tree, unsigned pos, unsigned _many) : many(_many), count(0), whichNext(pos-1), start(pos-1), current(NULL), tree(_tree)
- {
- tree.Link();
- }
- SingleIdIterator::~SingleIdIterator()
- {
- tree.Release();
- }
- void SingleIdIterator::setCurrent(unsigned pos)
- {
- current = tree.value->queryElement(pos);
- }
- // IInterface impl.
- bool SingleIdIterator::first()
- {
- whichNext = start;
- if (!tree.value || !tree.value->isArray())
- {
- if (0 == whichNext)
- {
- current = const_cast<PTree*>(&tree);
- count = 1;
- }
- }
- else
- {
- count = tree.value->elements();
- if (whichNext < count)
- setCurrent(whichNext);
- else
- return false;
- }
- ++whichNext;
- return true;
- }
- bool SingleIdIterator::next()
- {
- if ((whichNext>=count) || ((unsigned) -1 != many && whichNext>start+many))
- {
- current = NULL;
- return false;
- }
- setCurrent(whichNext++);
- return true;
- }
- bool SingleIdIterator::isValid()
- {
- return (NULL != current);
- }
- //////////////
- class StackElement
- {
- public:
- void init(IPropertyTreeIterator *_iter, const char *_xpath)
- {
- xpath = (char *)strdup(_xpath);
- iter=LINK(_iter);
- }
- void clear()
- {
- ::Release(iter);
- if (xpath)
- free(xpath);
- }
- IPropertyTreeIterator *get(StringAttr &str)
- {
- str.setown(xpath); return iter; // NB used in place of pop, as element invalid after call
- }
- IPropertyTreeIterator *iter;
- char * xpath;
- };
- ///////////////////
- PTStackIterator::PTStackIterator(IPropertyTreeIterator *_iter, const char *_xpath) : rootIter(_iter), xpath(_xpath)
- {
- iter = NULL;
- xxpath = "";
- current = NULL;
- stacklen = 0;
- stackmax = 4;
- stack = (StackElement *)malloc(sizeof(StackElement)*stackmax);
- }
- PTStackIterator::~PTStackIterator()
- {
- while (stacklen)
- stack[--stacklen].clear();
- ::Release(iter);
- ::Release(rootIter);
- free(stack);
- }
- void PTStackIterator::setIterator(IPropertyTreeIterator *_iter)
- {
- assertex(_iter);
- if (iter)
- iter->Release();
- iter = _iter;
- iter->first();
- }
- // IIterator impl.
- bool PTStackIterator::first()
- {
- while (stacklen)
- stack[--stacklen].clear();
- current = NULL;
- xxpath = xpath;
- rootIter->Link();
- setIterator(rootIter);
- return next();
- }
- bool PTStackIterator::isValid()
- {
- return (current != NULL);
- }
- IPropertyTree &PTStackIterator::query()
- {
- assertex(current);
- return *current;
- }
- bool PTStackIterator::next()
- {
- bool separator = false;
- if (iter)
- {
- IPropertyTree *element = NULL;
- StringBuffer qualifierText;
- for (;;)
- {
- while (!iter->isValid())
- {
- if (iter) iter->Release();
- iter = popFromStack(stackPath); // leaves linked
- if (!iter)
- {
- current = NULL;
- return false;
- }
- xxpath = stackPath;
- element = NULL;
- }
- if (!element)
- {
- element = &iter->query();
- iter->next();
- }
- while (element)
- {
- switch (*xxpath)
- {
- case '\0':
- current = element;
- return true;
- case '.':
- if (separator) throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Syntax error");
- separator=false;
- ++xxpath;
- if (*xpath && '/' != *xpath)
- throw MakeXPathException(xpath-1, PTreeExcpt_XPath_Unsupported, 0, "\"/\" expected");
- break;
- case '/':
- ++xxpath;
- if ('/' == *xxpath)
- {
- --xxpath;
- if (iter->isValid())
- pushToStack(iter, xxpath);
- setIterator(element->getElements(xxpath));
- xxpath = "";
- element = NULL;
- }
- separator=true;
- break;
- default:
- separator=false;
- if (iter->isValid())
- pushToStack(iter, xxpath);
- bool wild;
- const char *start = xxpath;
- readWildIdIndex(xxpath, wild);
- size32_t s = xxpath-start;
- if (s)
- {
- qualifierText.clear().append(s, start);
- setIterator(element->getElements(qualifierText));
- }
- else // must be qualifier.
- {
- if ('[' != *xxpath)
- throw MakeXPathException(xxpath, PTreeExcpt_XPath_ParseError, 0, "Qualifier expected e.g. [..]");
- const char *start = xxpath;
- char quote = 0;
- while (']' != *(++xxpath) || quote)
- {
- switch (*xxpath) {
- case '\"':
- case '\'':
- {
- if (quote)
- {
- if (*xxpath == quote)
- quote = 0;
- }
- else
- quote = *xxpath;
- break;
- }
- case '\0':
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xxpath-start, "Qualifier brace unclosed");
- }
- }
- ++xxpath;
- qualifierText.clear().append(xxpath-start, start);
- setIterator(element->getElements(qualifierText.str()));
- }
- element = NULL;
- break;
- }
- }
- }
- }
- return false;
- }
- void PTStackIterator::pushToStack(IPropertyTreeIterator *iter, const char *xpath)
- {
- if (stacklen==stackmax) {
- stackmax *= 2;
- stack = (StackElement *)realloc(stack, sizeof(StackElement)*stackmax);
- }
- stack[stacklen++].init(iter, xpath);
- }
- IPropertyTreeIterator *PTStackIterator::popFromStack(StringAttr &path)
- {
- if (!stacklen)
- return NULL;
- return stack[--stacklen].get(path);
- }
- #define DEFAULT_PTREE_TYPE LocalPTree
- // factory methods
- IPropertyTree *createPTree(MemoryBuffer &src, byte flags)
- {
- IPropertyTree *tree = createPTree(nullptr, flags);
- tree->deserialize(src);
- return tree;
- }
- IPropertyTree *createPTreeFromIPT(const IPropertyTree *srcTree, ipt_flags flags)
- {
- Owned<PTree> tree = (PTree *)createPTree(NULL, flags);
- return tree->clone(*srcTree->queryBranch(NULL));
- }
- void mergePTree(IPropertyTree *target, IPropertyTree *toMerge)
- {
- Owned<IAttributeIterator> aiter = toMerge->getAttributes();
- ForEach (*aiter)
- target->addProp(aiter->queryName(), aiter->queryValue());
- Owned<IPropertyTreeIterator> iter = toMerge->getElements("*");
- ForEach (*iter)
- {
- IPropertyTree &e = iter->query();
- target->addPropTree(e.queryName(), LINK(&e));
- }
- }
- void _synchronizePTree(IPropertyTree *target, IPropertyTree *source)
- {
- Owned<IAttributeIterator> aiter = target->getAttributes();
- StringArray targetAttrs;
- ForEach (*aiter)
- targetAttrs.append(aiter->queryName());
- aiter.setown(source->getAttributes());
- ForEach (*aiter)
- {
- const char *attr = aiter->queryName();
- if (!target->hasProp(attr))
- target->setProp(attr, aiter->queryValue());
- else
- {
- const char *sValue = aiter->queryValue();
- const char *tValue = target->queryProp(attr);
- if (NULL == sValue)
- {
- if (NULL != tValue)
- target->setProp(attr, sValue);
- }
- else if (NULL == tValue ||0 != strcmp(sValue, tValue))
- target->setProp(attr, sValue);
- targetAttrs.zap(attr);
- }
- }
- // remaining
- ForEachItemIn (a, targetAttrs)
- target->removeProp(targetAttrs.item(a));
-
- bool equal = true;
- MemoryBuffer srcMb;
- const char *src = NULL;
- if (target->isBinary())
- {
- MemoryBuffer tgtMb;
- target->getPropBin(NULL, tgtMb);
- source->getPropBin(NULL, srcMb);
- if (tgtMb.length() != srcMb.length())
- equal = false;
- else if (0 != memcmp(tgtMb.toByteArray(), srcMb.toByteArray(), tgtMb.length()))
- equal = false;
- }
- else
- {
- const char *tgt = target->queryProp(NULL);
- src = source->queryProp(NULL);
- unsigned lTgt = tgt?(size32_t)strlen(tgt):0;
- unsigned lSrc = src?(size32_t)strlen(src):0;
- if (lTgt != lSrc)
- equal = false;
- else if (0 != lTgt && (0 != strcmp(tgt, src)))
- equal = false;
- }
- if (!equal)
- {
- if (target->isBinary())
- target->setPropBin(NULL, srcMb.length(), srcMb.toByteArray());
- else
- target->setProp(NULL, src);
- }
-
- ICopyArrayOf<IPropertyTree> toProcess;
- Owned<IPropertyTreeIterator> iter = source->getElements("*");
- ForEach (*iter)
- toProcess.append(iter->query());
- iter.setown(target->getElements("*"));
- ICopyArrayOf<IPropertyTree> removeTreeList;
- Owned<IPropertyTreeIterator> srcTypeIter;
- StringAttr firstOfType;
- ForEach (*iter)
- {
- IPropertyTree &e = iter->query();
- const char *name = e.queryName();
- IPropertyTree *sourceCompare;
- if (!source->hasProp(name))
- {
- removeTreeList.append(e);
- firstOfType.clear();
- srcTypeIter.clear();
- }
- else
- {
- if (firstOfType.isEmpty() || 0 != strcmp(firstOfType, e.queryName()))
- {
- if (firstOfType.length() && srcTypeIter)
- {
- // add remaining
- while (srcTypeIter->next())
- {
- sourceCompare = &srcTypeIter->query();
- target->addPropTree(sourceCompare->queryName(), LINK(sourceCompare));
- toProcess.zap(*sourceCompare);
- }
- }
- srcTypeIter.setown(source->getElements(e.queryName()));
- firstOfType.set(e.queryName());
- assertex(srcTypeIter->first());
- sourceCompare = &srcTypeIter->query();
- }
- else // 2nd of type etc..
- sourceCompare = srcTypeIter->next() ? &srcTypeIter->query() : NULL;
- if (sourceCompare)
- {
- toProcess.zap(*sourceCompare);
- _synchronizePTree(&e, sourceCompare);
- }
- else
- removeTreeList.append(e);
- }
- }
- ForEachItemIn (rt, removeTreeList)
- target->removeTree(&removeTreeList.item(rt));
- // add unprocessed source elements, not reference by name in target
- ForEachItemIn (s, toProcess)
- {
- IPropertyTree &e = toProcess.item(s);
- target->addPropTree(e.queryName(), LINK(&e));
- }
- }
- // ensure target is equivalent to source whilst retaining elements already present in target.
- // presevers ordering of matching elements.
- void synchronizePTree(IPropertyTree *target, IPropertyTree *source)
- {
- const char *srcName = source->queryName();
- const char *tgtName = target->queryName();
- if (0 != strcmp(srcName, tgtName))
- throw MakeIPTException(PTreeExcpt_Unsupported, "Cannot synchronize if root nodes mismatch");
- _synchronizePTree(target, source);
- }
- IPropertyTree *ensurePTree(IPropertyTree *root, const char *xpath)
- {
- return createPropBranch(root, xpath, true);
- }
- IPTreeReadException *createPTreeReadException(int code, const char *msg, const char *context, unsigned line, offset_t offset)
- {
- //Do not use jlib_thrown_decl because it causes problems with VS2017 - I think because of beforeDispose() in CInterfaceOf.
- //The type of the object actually thrown is IPTreeReadException which does have a jlib_thrown_decl - so it will still be caught.
- class CPTreeReadException : implements CInterfaceOf<IPTreeReadException>
- {
- int code;
- StringAttr msg;
- StringAttr context;
- unsigned line;
- offset_t offset;
- StringBuffer &getErrorMessage(StringBuffer &out) const
- {
- switch (code)
- {
- case PTreeRead_EOS:
- return out.append("Error - end of stream");
- case PTreeRead_syntax:
- return out.append("Error - syntax error");
- }
- return out;
- }
- public:
- CPTreeReadException(int _code, const char *_msg, const char *_context, unsigned _line, offset_t _offset) : code(_code), msg(_msg), context(_context), line(_line), offset(_offset) { }
- // IException
- int errorCode() const { return code; }
- StringBuffer &errorMessage(StringBuffer &str) const
- {
- getErrorMessage(str);
- if (msg.length())
- str.append(" \"").append(msg).append("\"");
- str.append(" [");
- if (line>1) // don't bother with line 1, there may be no line breaks.
- str.append("line ").append(line).append(", ");
- str.append("file offset ").append(offset).append("]");
- if (context.length())
- str.newline().append(context);
- return str;
- }
- MessageAudience errorAudience() const { return MSGAUD_user; }
-
- const char *queryDescription() { return msg; }
- unsigned queryLine() { return line; }
- offset_t queryOffset() { return offset; }
- const char *queryContext() { return context.get(); }
- };
- return new CPTreeReadException(code, msg, context, line, offset);
- }
- template <typename T>
- class CommonReaderBase : public CInterface
- {
- Linked<ISimpleReadStream> lstream;
- ISimpleReadStream *stream;
- bool bufOwned, nullTerm;
- byte *buf, *bufPtr;
- size32_t bufSize, bufRemaining;
- protected:
- PTreeReaderOptions readerOptions;
- bool ignoreWhiteSpace, noRoot;
- Linked<IPTreeNotifyEvent> iEvent;
- offset_t curOffset;
- unsigned line;
- char nextChar;
- private:
- void init()
- {
- ignoreWhiteSpace = 0 != ((unsigned)readerOptions & (unsigned)ptr_ignoreWhiteSpace);
- noRoot = 0 != ((unsigned)readerOptions & (unsigned)ptr_noRoot);
- }
- void resetState()
- {
- bufPtr = buf;
- nextChar = 0;
- if (nullTerm || stream)
- bufRemaining = 0;
- curOffset = 0;
- line = 0;
- }
- public:
- CommonReaderBase(ISimpleReadStream &_stream, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions, size32_t _bufSize=0) :
- bufSize(_bufSize), readerOptions(_readerOptions), iEvent(&_iEvent)
- {
- if (!bufSize) bufSize = 0x8000;
- buf = new byte[bufSize];
- bufRemaining = 0;
- curOffset = 0;
- bufOwned = true;
- nullTerm = false;
- lstream.set(&_stream);
- stream = &_stream; // for efficiency
- init();
- resetState();
- }
- CommonReaderBase(const void *_buf, size32_t bufLength, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
- readerOptions(_readerOptions), iEvent(&_iEvent)
- {
- bufSize = 0; // not used for direct reads
- stream = NULL; // not used for direct reads
- bufRemaining = bufLength;
- nullTerm = false;
- buf = (byte *)_buf;
- bufOwned = false;
- init();
- resetState();
- }
- CommonReaderBase(const void *_buf, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
- readerOptions(_readerOptions), iEvent(&_iEvent)
- {
- bufSize = 0; // not used for direct reads
- stream = NULL; // not used for direct reads
- curOffset = 0;
- bufRemaining = 0;
- nullTerm = true;
- buf = (byte *)_buf;
- bufOwned = false;
- init();
- resetState();
- }
- ~CommonReaderBase()
- {
- if (bufOwned)
- delete [] buf;
- }
- protected:
- virtual void reset()
- {
- resetState();
- }
- void rewind(size32_t n)
- {
- assertex(curOffset >= n);
- if (!n) return;
- curOffset -= n;
- size32_t d = (size32_t)(bufPtr-buf);
- if (n > d) n = d;
- if (!nullTerm)
- bufRemaining += n;
- for (;;)
- {
- --bufPtr;
- if (!--n) break;
- if (10 == *bufPtr) --line;
- }
- }
- bool checkBOM()
- {
- bool utf16 = false;
- bool utf8 = false;
- // Note - technically the utf16 LE case could also be utf32 LE (utf32 BE would be 0x00 0x00 0xfe 0xff)
- // But utf32 is so rare that we ignore it for now
- switch ((unsigned char)nextChar)
- {
- case 0xff:
- readNext();
- if (0xfe == (unsigned char)nextChar)
- utf16 = true;
- break;
- case 0xfe:
- readNext();
- if (0xff == (unsigned char)nextChar)
- utf16 = true;
- break;
- case 0xef:
- readNext();
- if (0xbb == (unsigned char)nextChar)
- {
- readNext();
- if (0xbf == (unsigned char)nextChar)
- utf8 = true;
- }
- break;
- default:
- break;
- }
- if (utf8)
- return true;
- else if (utf16)
- error("Unsupported utf16 format detected in BOM header", false);
- return false;
- }
- inline void expecting(const char *str)
- {
- StringBuffer errorMsg("Expecting \"");
- error(errorMsg.append(str).append("\"").str());
- }
- inline void eos()
- {
- error("String terminator hit");
- }
- void match(const char *txt, const char *msg=NULL)
- {
- const char *c = txt;
- for (;;)
- {
- if (*c == '\0') break;
- readNext();
- if (toupper(nextChar) != toupper(*c))
- {
- if (msg)
- error(msg);
- throw c;
- }
- c++;
- }
- }
- void error(const char *msg=NULL, bool giveContext=true, PTreeReadExcptCode code=PTreeRead_syntax)
- {
- StringBuffer context;
- if (giveContext)
- {
- size32_t bufPos = (size32_t)(bufPtr-buf);
- unsigned preLen = std::min(40U, bufPos);
- size32_t bR = bufRemaining;
- if (nullTerm)
- {
- byte *tPtr = bufPtr;
- while (bR<40)
- {
- if ('\0' == *tPtr++) break;
- bR++;
- }
- }
- unsigned postLen = std::min(80-preLen, bR);
- const char *bufferContext = (const char *)(bufPtr - preLen);
- context.append(preLen, bufferContext);
- context.append("*ERROR*");
- context.append(postLen, bufferContext+preLen);
- }
- throw createPTreeReadException(code, msg, context.str(), line+1, curOffset);
- }
- inline void readNext()
- {
- if (!readNextToken())
- error("End of stream encountered whilst parsing", true, PTreeRead_EOS);
- curOffset++;
- }
- inline bool checkReadNext()
- {
- if (!readNextToken())
- return false;
- curOffset++;
- return true;
- }
- inline bool checkStartReadNext()
- {
- if (curOffset || nextChar) //not at starting state
- return true;
- return readNextToken();
- }
- inline bool readNextToken();
- inline bool checkSkipWS()
- {
- while (isspace(nextChar)) if (!checkReadNext()) return false;
- return true;
- }
- inline void skipWS()
- {
- while (isspace(nextChar)) readNext();
- }
- };
- class CInstStreamReader { public: }; // only used to ensure different template definitions.
- class CInstBufferReader { public: };
- class CInstStringReader { public: };
- template <> inline bool CommonReaderBase<CInstStreamReader>::readNextToken()
- {
- // do own buffering, to have reasonable error context.
- if (0 == bufRemaining)
- {
- size32_t _bufRemaining = stream->read(bufSize, buf);
- if (!_bufRemaining)
- return false;
- bufRemaining = _bufRemaining;
- bufPtr = buf;
- }
- --bufRemaining;
- nextChar = *bufPtr++;
- if (10 == nextChar)
- line++;
- return true;
- }
- template <> inline bool CommonReaderBase<CInstBufferReader>::readNextToken()
- {
- if (0 == bufRemaining)
- return false;
- --bufRemaining;
- nextChar = *bufPtr++;
- if (10 == nextChar)
- line++;
- return true;
- }
- template <> inline bool CommonReaderBase<CInstStringReader>::readNextToken()
- {
- nextChar = *bufPtr++;
- if ('\0' == nextChar)
- {
- --bufPtr;
- return false;
- }
- if (10 == nextChar)
- line++;
- return true;
- }
- template <typename X>
- class CXMLReaderBase : public CommonReaderBase<X>, implements IEntityHelper
- {
- StringAttrMapping entityTable;
- protected:
- bool ignoreNameSpaces;
- bool hadXMLDecl;
- private:
- void init()
- {
- ignoreNameSpaces = 0 != ((unsigned) readerOptions & (unsigned)ptr_ignoreNameSpaces);
- }
- void resetState()
- {
- hadXMLDecl = false;
- }
- public:
- typedef CommonReaderBase<X> PARENT;
- using PARENT::nextChar;
- using PARENT::readNext;
- using PARENT::expecting;
- using PARENT::match;
- using PARENT::error;
- using PARENT::skipWS;
- using PARENT::rewind;
- using PARENT::readerOptions;
- CXMLReaderBase(ISimpleReadStream &_stream, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _xmlReaderOptions, size32_t _bufSize=0)
- : CommonReaderBase<X>(_stream, _iEvent, _xmlReaderOptions, _bufSize)
- {
- init();
- resetState();
- }
- CXMLReaderBase(const void *_buf, size32_t bufLength, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _xmlReaderOptions)
- : CommonReaderBase<X>(_buf, bufLength, _iEvent, _xmlReaderOptions)
- {
- init();
- resetState();
- }
- CXMLReaderBase(const void *_buf, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _xmlReaderOptions)
- : CommonReaderBase<X>(_buf, _iEvent, _xmlReaderOptions)
- {
- init();
- resetState();
- }
- protected:
- virtual void reset() override
- {
- resetState();
- PARENT::reset();
- }
- void readID(StringBuffer &id)
- {
- if (isValidXPathStartChr(nextChar))
- {
- for (;;)
- {
- id.append(nextChar);
- readNext();
- if (!isValidXPathChr(nextChar)) break;
- }
- }
- }
- void skipString()
- {
- if ('"' == nextChar)
- {
- do { readNext(); } while ('"' != nextChar);
- }
- else if ('\'' == nextChar)
- {
- do { readNext(); } while ('\'' != nextChar);
- }
- else expecting("\" or '");
- }
- bool lookupRefValue(const char *name, StringBuffer &value)
- {
- StringAttr *val = entityTable.getValue(name);
- if (!val) return false;
- value.append(*val);
- return true;
- }
- void storeEntity(const char *name, const char *value)
- {
- entityTable.setValue(name, value);
- }
- void parseEntity()
- {
- try { match("NTITY"); }
- catch (const char *) { error("Bad syntax"); }
- readNext();
- skipWS();
- StringBuffer entityName;
- if ('%' != nextChar)
- {
- readID(entityName);
- skipWS();
- if ('"' == nextChar)
- {
- StringBuffer refValue;
- for (;;)
- {
- readNext();
- if (!nextChar || '"' == nextChar)
- break;
- if ('&' == nextChar)
- {
- readNext();
- StringBuffer ref;
- if ('#' == nextChar)
- {
- ref.append("&#");
- for (;;)
- {
- readNext();
- if (!nextChar)
- expecting(";");
- if (';' == nextChar) break;
- ref.append(nextChar);
- }
- ref.append(";");
- decodeXML(ref, refValue);
- }
- else
- {
- readID(ref);
- if (';' != nextChar)
- expecting(";");
- if (!lookupRefValue(ref, refValue))
- {
- StringBuffer _ref("&");
- _ref.append(ref).append(';');
- decodeXML(ref, refValue); // try inbuilts
- }
- }
- }
- else
- refValue.append(nextChar);
- }
- storeEntity(entityName, refValue);
- }
- }
- do { readNext(); }
- while (nextChar && nextChar != '>');
- }
- void parseIntSubset()
- {
- for (;;)
- {
- readNext();
- skipWS();
- if (']'== nextChar) break;
- if ('<' == nextChar)
- {
- readNext();
- switch (nextChar)
- {
- case '!':
- {
- readNext();
- switch (nextChar)
- {
- case '-':
- parseComment();
- break;
- case 'E':
- parseEntity();
- break;
- default: // ignore anything else
- do { readNext(); }
- while (nextChar && nextChar != '>');
- break;
- }
- break;
- }
- case '?':
- {
- StringBuffer pi;
- parsePI(pi);
- break;
- }
- }
- }
- }
- }
- void parseOther()
- {
- switch (nextChar)
- {
- case '-':
- parseComment2();
- break;
- case 'D':
- {
- try { match("OCTYPE"); }
- catch (const char *) { error("Bad syntax"); }
- readNext();
- skipWS();
- StringBuffer doctypeid;
- readID(doctypeid);
- for (;;)
- {
- skipWS();
- if ('>' == nextChar) break;
- if ('[' == nextChar)
- {
- parseIntSubset();
- if (']' != nextChar)
- expecting("]");
- }
- else if ('S' == nextChar)
- {
- match("YSTEM");
- readNext();
- skipWS();
- skipString();
- }
- else if ('P' == nextChar)
- {
- match("UBLIC");
- readNext();
- skipWS();
- skipString();
- readNext();
- skipWS();
- skipString();
- }
- readNext();
- }
- break;
- }
- default:
- error("Invalid information tag");
- }
- }
- void parsePIOrDecl()
- {
- StringBuffer target;
- parsePI(target);
- if (0 == strcmp("xml", target.str()))
- {
- if (hadXMLDecl)
- error("Only one XML declartion permitted");
- hadXMLDecl = true;
- }
- }
- void parseCData(StringBuffer &text)
- {
- try { match("CDATA["); }
- catch (const char *) { error("Bad CDATA syntax"); }
- for (;;)
- {
- readNext();
- while (']' == nextChar)
- {
- readNext();
- while (']' == nextChar)
- {
- readNext();
- if ('>' == nextChar)
- return;
- else
- text.append(']');
- }
- text.append(']');
- }
- text.append(nextChar);
- }
- }
- void parsePI(StringBuffer &target)
- {
- readNext();
- if (!isValidXPathStartChr(nextChar))
- error("Invalid PI target");
- for (;;)
- {
- target.append(nextChar);
- readNext();
- if (!isValidXPathChr(nextChar))
- break;
- }
- skipWS();
- unsigned closeTag=0;
- for (;;)
- {
- if (!nextChar)
- error("Missing closing PI tag ?>");
- if (1 == closeTag)
- {
- if ('>' == nextChar)
- break;
- closeTag = 0;
- }
- else if ('?' == nextChar)
- closeTag = 1;
- readNext();
- }
- }
- void parseDirective(StringBuffer &res)
- {
- readNext();
- switch (nextChar) {
- case '-':
- parseComment2();
- break;
- case '[':
- parseCData(res);
- break;
- default:
- error("Unrecognised syntax");
- }
- }
- void parseComment()
- {
- readNext();
- if (nextChar != '-') error("Bad comment syntax");
- parseComment2();
- }
- void parseComment2()
- {
- readNext();
- if (nextChar != '-') error("Bad comment syntax");
- readNext();
- unsigned seen = 0;
- while (nextChar)
- {
- if (seen==2)
- {
- if (nextChar=='>')
- return;
- else if (nextChar != '-') // should be syntax error really.
- seen = 0;
- }
- else if (nextChar=='-')
- seen++;
- else
- seen = 0;
- readNext();
- }
- error("Bad comment syntax");
- }
- const char *_decodeXML(unsigned read, const char *startMark, StringBuffer &ret)
- {
- const char *errMark = NULL;
- try { return decodeXML(startMark, ret, &errMark, this); }
- catch (IException *e)
- {
- if (errMark)
- rewind((unsigned)(errMark-startMark));
- StringBuffer errMsg;
- e->errorMessage(errMsg);
- e->Release();
- error(errMsg.str());
- }
- return NULL; // will never get here.
- }
- // IEntityHelper impl.
- virtual bool find(const char *entity, StringBuffer &value) override
- {
- return lookupRefValue(entity, value);
- }
- };
- template <class X>
- class CXMLReader : public CXMLReaderBase<X>, implements IPTreeReader
- {
- bool rootTerminated;
- StringBuffer attrName, attrval;
- StringBuffer tmpStr;
- void init()
- {
- attrName.append('@');
- }
- void resetState()
- {
- rootTerminated = false;
- }
- public:
- typedef CXMLReaderBase<X> PARENT;
- using PARENT::nextChar;
- using PARENT::readNext;
- using PARENT::expecting;
- using PARENT::match;
- using PARENT::error;
- using PARENT::skipWS;
- using PARENT::checkBOM;
- using PARENT::checkReadNext;
- using PARENT::checkSkipWS;
- using PARENT::eos;
- using PARENT::curOffset;
- using PARENT::noRoot;
- using PARENT::ignoreWhiteSpace;
- using PARENT::iEvent;
- using PARENT::parseDirective;
- using PARENT::parseOther;
- using PARENT::parsePI;
- using PARENT::parsePIOrDecl;
- using PARENT::parseComment;
- using PARENT::_decodeXML;
- using PARENT::ignoreNameSpaces;
- using PARENT::hadXMLDecl;
- IMPLEMENT_IINTERFACE;
- CXMLReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize=0)
- : PARENT(stream, iEvent, xmlReaderOptions, bufSize)
- {
- init();
- resetState();
- }
- CXMLReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
- : PARENT(buf, bufLength, iEvent, xmlReaderOptions)
- {
- init();
- resetState();
- }
- CXMLReader(const void *buf, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
- : PARENT(buf, iEvent, xmlReaderOptions)
- {
- init();
- resetState();
- }
- virtual void reset() override
- {
- resetState();
- PARENT::reset();
- }
- // IPTreeReader
- virtual void load() override { loadXML(); }
- virtual offset_t queryOffset() override { return curOffset; }
- void loadXML()
- {
- bool head=true;
- restart:
- if (!checkReadNext()) return;
- if (head)
- {
- head = false;
- if (checkBOM())
- if (!checkReadNext()) return;
- }
- if (!checkSkipWS()) return;
- if ('<' != nextChar)
- expecting("<");
- readNext();
- if ('!' == nextChar)
- {
- readNext();
- parseOther();
- goto restart;
- }
- else if ('?' == nextChar)
- {
- parsePIOrDecl();
- goto restart;
- }
- if (!noRoot && rootTerminated)
- {
- if (ignoreWhiteSpace)
- if (!checkSkipWS()) return;
- error("Trailing xml after close of root tag");
- }
- _loadXML();
- if (noRoot)
- {
- head = true;
- hadXMLDecl = false;
- }
- else
- rootTerminated = true;
- goto restart;
- }
- void _loadXML()
- {
- restart:
- offset_t startOffset = curOffset-2;
- if ('!' == nextChar) // not sure this branch can ever be hit.
- {
- parseComment();
- readNext();
- if ('<' != nextChar)
- expecting("<");
- goto restart;
- }
- StringBuffer tagName;
- if (ignoreWhiteSpace)
- skipWS();
- while (!isspace(nextChar) && nextChar != '>' && nextChar != '/')
- {
- tagName.append(nextChar);
- readNext();
- if ('<' == nextChar)
- error("Unmatched close tag encountered");
- }
- StringBuffer completeTagname = tagName;
- if (ignoreNameSpaces)
- {
- const char *colon;
- if ((colon = strchr(tagName.str(), ':')) != NULL)
- tagName.remove(0, (size32_t)(colon - tagName.str() + 1));
- }
- iEvent->beginNode(tagName.str(), startOffset);
- skipWS();
- bool endTag = false;
- bool base64 = false;
- while(nextChar != '>')
- {
- skipWS();
- if (nextChar=='/')
- {
- readNext();
- if (nextChar != '>')
- expecting(">");
- endTag = true;
- break;
- }
- attrName.setLength(1);
- attrval.clear();
- while (nextChar && !isspace(nextChar) && nextChar != '=' && nextChar != '>' && nextChar != '/')
- {
- attrName.append(nextChar);
- readNext();
- }
- skipWS();
- if (nextChar == '=') readNext(); else expecting("=");
- skipWS();
- if (nextChar == '"')
- {
- readNext();
- while (nextChar != '"')
- {
- if (!nextChar)
- eos();
- attrval.append(nextChar);
- readNext();
- }
- }
- else if (nextChar == '\'')
- {
- readNext();
- while (nextChar != '\'')
- {
- attrval.append(nextChar);
- readNext();
- }
- }
- else
- error();
- _decodeXML(0, attrval.str(), tmpStr.clear());
- if (0 == strcmp(attrName.str(), "@xsi:type") &&
- (0 == stricmp(tmpStr.str(),"SOAP-ENC:base64")))
- base64 = true;
- else
- iEvent->newAttribute(attrName.str(), tmpStr.str());
- readNext();
- skipWS();
- }
- iEvent->beginNodeContent(tagName.str());
- StringBuffer tagText;
- bool binary = base64;
- if (!endTag)
- {
- if (nextChar == '>')
- {
- for (;;)
- {
- for (;;)
- {
- readNext();
- if (ignoreWhiteSpace)
- skipWS();
- if ('\0' == nextChar)
- eos();
- StringBuffer mark;
- while (nextChar && nextChar !='<') { mark.append(nextChar); readNext(); }
- size32_t l = mark.length();
- size32_t r = l+1;
- if (l)
- {
- if (ignoreWhiteSpace)
- {
- while (l-- && isspace(mark.charAt(l)));
- mark.setLength(l+1);
- }
- tagText.ensureCapacity(mark.length());
- _decodeXML(r, mark.str(), tagText);
- }
- readNext();
- if ('!' == nextChar)
- parseDirective(tagText);
- else if ('?' == nextChar)
- {
- parsePI(tmpStr.clear());
- #ifdef STRICT_PI
- if (0 == stricmp(tmpStr.str(), "xml"))
- error("Reserved PI target used");
- #endif
- }
- else
- break;
- }
- if (nextChar=='/')
- {
- if (base64)
- {
- JBASE64_Decode(tagText.str(), tmpStr.clear());
- tagText.swapWith(tmpStr);
- }
- else
- {
- if (strlen(tagText.str()) != tagText.length())
- binary = true;
- }
- break; // exit
- }
- else
- _loadXML();
- }
- readNext();
- unsigned i = 0;
- while (!isspace(nextChar) && nextChar != '>')
- {
- if ((i >= completeTagname.length()) ||
- (nextChar != completeTagname.charAt(i++)))
- error("Mismatched opening and closing tags");
- readNext();
- }
- if (i != completeTagname.length())
- error("Mismatched opening and closing tags");
- skipWS();
- if (nextChar != '>')
- expecting(">");
- }
- }
- iEvent->endNode(tagName.str(), tagText.length(), tagText.str(), binary, curOffset);
- }
- };
- template <class X>
- class CPullXMLReader : public CXMLReaderBase<X>, implements IPullPTreeReader
- {
- typedef CXMLReaderBase<X> PARENT;
- using PARENT::nextChar;
- using PARENT::readNext;
- using PARENT::expecting;
- using PARENT::match;
- using PARENT::error;
- using PARENT::skipWS;
- using PARENT::checkBOM;
- using PARENT::checkReadNext;
- using PARENT::checkSkipWS;
- using PARENT::eos;
- using PARENT::curOffset;
- using PARENT::noRoot;
- using PARENT::ignoreWhiteSpace;
- using PARENT::iEvent;
- using PARENT::parseDirective;
- using PARENT::parseOther;
- using PARENT::parsePI;
- using PARENT::parsePIOrDecl;
- using PARENT::parseComment;
- using PARENT::_decodeXML;
- using PARENT::ignoreNameSpaces;
- using PARENT::hadXMLDecl;
- class CStateInfo : public CInterface
- {
- public:
- CStateInfo()
- {
- tag.ensureCapacity(15);
- binary = base64 = false;
- }
- inline void reset()
- {
- binary = base64 = false;
- tag.clear();
- tagText.clear();
- }
- const char *wnsTag;
- StringBuffer tag;
- StringBuffer tagText;
- bool binary, base64;
- };
- CICopyArrayOf<CStateInfo> stack, freeStateInfo;
- CStateInfo *stateInfo;
- enum ParseStates { headerStart, tagStart, tagAttributes, tagContent, tagContent2, tagClose, tagEnd, tagMarker } state;
- bool endOfRoot;
- StringBuffer attrName, attrval, mark, tmpStr;
- void resetState()
- {
- stack.kill();
- state = headerStart;
- stateInfo = NULL;
- endOfRoot = false;
- attrName.append('@');
- }
- public:
- IMPLEMENT_IINTERFACE;
- CPullXMLReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize=0)
- : CXMLReaderBase<X>(stream, iEvent, xmlReaderOptions, bufSize)
- {
- resetState();
- }
- CPullXMLReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
- : CXMLReaderBase<X>(buf, bufLength, iEvent, xmlReaderOptions)
- {
- resetState();
- }
- CPullXMLReader(const void *buf, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
- : CXMLReaderBase<X>(buf, iEvent, xmlReaderOptions)
- {
- resetState();
- }
- ~CPullXMLReader()
- {
- ForEachItemIn(i, stack)
- delete &stack.item(i);
- ForEachItemIn(i2, freeStateInfo)
- delete &freeStateInfo.item(i2);
- }
- // IPullPTreeReader
- virtual void load() override
- {
- while (next()) {}
- }
- virtual void reset() override
- {
- PARENT::reset();
- resetState();
- }
- virtual offset_t queryOffset() override { return curOffset; }
- virtual bool next() override
- {
- switch (state)
- {
- case headerStart:
- {
- if (!checkReadNext()) return false;
- if (checkBOM())
- if (!checkReadNext()) return false;
- for (;;)
- {
- if (!checkSkipWS()) return false;
- if ('<' != nextChar)
- expecting("<");
- readNext();
- if ('!' == nextChar)
- {
- readNext();
- parseOther();
- }
- else if ('?' == nextChar)
- parsePIOrDecl();
- else
- break;
- if (!checkReadNext()) return false;
- }
- state = tagStart;
- break;
- }
- case tagStart:
- {
- offset_t startOffset;
- for (;;)
- {
- if ('!' != nextChar)
- break;
- parseComment();
- readNext();
- if ('<' != nextChar)
- expecting("<");
- }
- startOffset = curOffset-2;
- if (freeStateInfo.ordinality())
- {
- stateInfo = &freeStateInfo.popGet();
- stateInfo->reset();
- }
- else
- stateInfo = new CStateInfo;
- stack.append(*stateInfo);
- if ('/' == nextChar)
- error("Unmatched close tag encountered");
- while (!isspace(nextChar) && nextChar != '>')
- {
- stateInfo->tag.append(nextChar);
- readNext();
- if ('/' == nextChar) break;
- if ('<' == nextChar)
- error("Unmatched close tag encountered");
- }
- stateInfo->wnsTag = stateInfo->tag.str();
- if (ignoreNameSpaces)
- {
- const char *colon;
- if ((colon = strchr(stateInfo->wnsTag, ':')) != NULL)
- stateInfo->wnsTag = colon+1;
- }
- endOfRoot = false;
- try
- {
- iEvent->beginNode(stateInfo->wnsTag, startOffset);
- }
- catch (IPTreeException *pe)
- {
- if (PTreeExcpt_InvalidTagName == pe->errorCode())
- {
- pe->Release();
- StringBuffer msg("Expecting valid start tag, but got \"");
- error(msg.append(stateInfo->wnsTag).append("\"").str());
- }
- throw;
- }
- state = tagAttributes;
- break;
- }
- case tagAttributes:
- {
- skipWS();
- if (nextChar == '>')
- state = tagContent;
- else
- {
- skipWS();
- if (nextChar=='/')
- {
- readNext();
- if (nextChar != '>')
- expecting(">");
- // no actual content
- iEvent->beginNodeContent(stateInfo->wnsTag);
- state = tagEnd;
- break;
- }
- attrName.setLength(1);
- attrval.clear();
- while (nextChar && !isspace(nextChar) && nextChar != '=' && nextChar != '>' && nextChar != '/')
- {
- attrName.append(nextChar);
- readNext();
- }
- skipWS();
- if (nextChar == '=') readNext(); else expecting("=");
- skipWS();
- if (nextChar == '"')
- {
- readNext();
- while (nextChar != '"')
- {
- if (!nextChar)
- eos();
- attrval.append(nextChar);
- readNext();
- }
- }
- else if (nextChar == '\'')
- {
- readNext();
- while (nextChar != '\'')
- {
- attrval.append(nextChar);
- readNext();
- }
- }
- else
- error();
- _decodeXML(0, attrval.str(), tmpStr.clear());
- if (0 == strcmp(attrName.str(), "@xsi:type") &&
- (0 == stricmp(tmpStr.str(),"SOAP-ENC:base64")))
- stateInfo->base64 = true;
- else
- iEvent->newAttribute(attrName.str(), tmpStr.str());
- readNext();
- skipWS();
- }
- break;
- }
- case tagContent:
- {
- iEvent->beginNodeContent(stateInfo->wnsTag);
- if ('>' != nextChar)
- state = tagEnd;
- else
- state = tagContent2;
- break;
- }
- case tagContent2:
- {
- try
- {
- for (;;)
- {
- if (endOfRoot)
- {
- if (!checkReadNext()) return false;
- if (!checkSkipWS()) return false;
- }
- else
- {
- readNext();
- if (ignoreWhiteSpace)
- skipWS();
- }
- if ('\0' == nextChar)
- eos();
- mark.clear();
- state = tagMarker;
- while (nextChar && nextChar !='<') { mark.append(nextChar); readNext(); }
- if (!nextChar)
- break;
- size32_t l = mark.length();
- size32_t r = l+1;
- if (l && stateInfo)
- {
- if (ignoreWhiteSpace)
- {
- const char *tb = mark.str();
- const char *t = tb+l-1;
- if (isspace(*t))
- {
- while (t != tb && isspace(*(--t)));
- mark.setLength((size32_t)(t-tb+1));
- }
- }
- stateInfo->tagText.ensureCapacity(mark.length());
- _decodeXML(r, mark.str(), stateInfo->tagText);
- }
- if (endOfRoot && mark.length())
- {
- const char *m = mark.str();
- const char *e = m+mark.length();
- do { if (!isspace(*m++)) error("Trailing content after close of root tag"); }
- while (m!=e);
- }
- readNext();
- if ('!' == nextChar)
- {
- parseDirective(stateInfo->tagText);
- state = tagContent2;
- }
- else if ('?' == nextChar)
- {
- parsePI(tmpStr.clear());
- #ifdef STRICT_PI
- if (0 == stricmp(tmpStr.str(), "xml"))
- error("Reserved PI target used");
- #endif
- state = tagContent2;
- }
- else
- break;
- }
- }
- catch (IPTreeReadException *e)
- {
- if (endOfRoot && PTreeRead_EOS == e->errorCode() && (state != tagContent2 && mark.length())) // only to provide more meaningful error
- {
- const char *m = mark.str();
- const char *es = m+mark.length();
- do
- {
- if (!isspace(*m++))
- {
- e->Release();
- error("Trailing content after close of root tag");
- }
- }
- while (m!=es);
- }
- throw;
- }
- if ('/' == nextChar)
- {
- if (endOfRoot && !noRoot)
- error("Trailing tag close after close of root tag");
- if (stateInfo->base64)
- {
- JBASE64_Decode(stateInfo->tagText.str(), tmpStr.clear());
- stateInfo->tagText.swapWith(tmpStr);
- stateInfo->binary = true;
- // next state tagContent2 still
- }
- else
- {
- if (strlen(stateInfo->tagText.str()) != stateInfo->tagText.length())
- stateInfo->binary = true;
- }
- state = tagClose;
- break; // exit
- }
- else
- {
- if (endOfRoot && !noRoot)
- error("Trailing tag open after close of root tag");
- state = tagStart;
- }
- break;
- }
- case tagClose:
- {
- readNext();
- const char *t = stateInfo->tag.str();
- const char *te = t+stateInfo->tag.length();
- for (;;)
- {
- if (nextChar == '>' || isspace(nextChar))
- {
- if (t != te)
- error("Mismatched opening and closing tags");
- break;
- }
- else if (nextChar != *t++)
- error("Mismatched opening and closing tags");
- readNext();
- }
- skipWS();
- if (nextChar != '>')
- expecting(">");
- state = tagEnd;
- break;
- }
- case tagEnd:
- {
- iEvent->endNode(stateInfo->wnsTag, stateInfo->tagText.length(), stateInfo->tagText.str(), stateInfo->binary, curOffset);
- freeStateInfo.append(*stateInfo);
- stack.pop();
- endOfRoot = 0==stack.ordinality();
- stateInfo = stack.ordinality()?&stack.tos():NULL;
- if (endOfRoot && noRoot)
- {
- state = headerStart;
- hadXMLDecl = false;
- endOfRoot = false;
- }
- else
- state = tagContent2;
- break;
- }
- }
- return true;
- }
- };
- IPTreeReader *createXMLStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize)
- {
- class CXMLStreamReader : public CXMLReader<CInstStreamReader>
- {
- public:
- CXMLStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize=0) : CXMLReader<CInstStreamReader>(stream, iEvent, xmlReaderOptions, bufSize) { }
- };
- return new CXMLStreamReader(stream, iEvent, xmlReaderOptions, bufSize);
- }
- IPTreeReader *createXMLStringReader(const char *xml, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
- {
- class CXMLStringReader : public CXMLReader<CInstStringReader>
- {
- public:
- CXMLStringReader(const void *xml, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions) : CXMLReader<CInstStringReader>(xml, iEvent, xmlReaderOptions) { }
- };
- if (NULL == xml)
- throw createPTreeReadException(PTreeRead_syntax, "Null string passed to createXMLStringReader", NULL, 0, 0);
- return new CXMLStringReader(xml, iEvent, xmlReaderOptions);
- }
- IPTreeReader *createXMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
- {
- class CXMLBufferReader : public CXMLReader<CInstBufferReader>
- {
- public:
- CXMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions) : CXMLReader<CInstBufferReader>(buf, bufLength, iEvent, xmlReaderOptions) { }
- };
- return new CXMLBufferReader(buf, bufLength, iEvent, xmlReaderOptions);
- }
- IPullPTreeReader *createPullXMLStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize)
- {
- class CXMLStreamReader : public CPullXMLReader<CInstStreamReader>
- {
- public:
- CXMLStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions, size32_t bufSize=0) : CPullXMLReader<CInstStreamReader>(stream, iEvent, xmlReaderOptions, bufSize) { }
- };
- return new CXMLStreamReader(stream, iEvent, xmlReaderOptions, bufSize);
- }
- IPullPTreeReader *createPullXMLStringReader(const char *xml, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
- {
- class CXMLStringReader : public CPullXMLReader<CInstStringReader>
- {
- public:
- CXMLStringReader(const void *xml, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions) : CPullXMLReader<CInstStringReader>(xml, iEvent, xmlReaderOptions) { }
- };
- return new CXMLStringReader(xml, iEvent, xmlReaderOptions);
- }
- IPullPTreeReader *createPullXMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions)
- {
- class CXMLBufferReader : public CPullXMLReader<CInstBufferReader>
- {
- public:
- CXMLBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions xmlReaderOptions) : CPullXMLReader<CInstBufferReader>(buf, bufLength, iEvent, xmlReaderOptions) { }
- };
- return new CXMLBufferReader(buf, bufLength, iEvent, xmlReaderOptions);
- }
- IPTreeMaker *createPTreeMaker(byte flags, IPropertyTree *root, IPTreeNodeCreator *nodeCreator)
- {
- return new CPTreeMaker(flags, nodeCreator, root);
- }
- IPTreeMaker *createRootLessPTreeMaker(byte flags, IPropertyTree *root, IPTreeNodeCreator *nodeCreator)
- {
- return new CPTreeMaker(flags, nodeCreator, root, true);
- }
- ////////////////////////////
- ///////////////////////////
- static IPTreeMaker *createDefaultPTreeMaker(byte flags, PTreeReaderOptions readFlags)
- {
- bool noRoot = 0 != ((unsigned)readFlags & (unsigned)ptr_noRoot);
- return new CPTreeMaker(flags, NULL, NULL, noRoot);
- }
- IPropertyTree *createPTree(ISimpleReadStream &stream, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
- {
- Owned<IPTreeMaker> _iMaker;
- if (!iMaker)
- {
- iMaker = createDefaultPTreeMaker(flags, readFlags);
- _iMaker.setown(iMaker);
- }
- Owned<IPTreeReader> reader = createXMLStreamReader(stream, *iMaker, readFlags);
- reader->load();
- if (iMaker->queryRoot())
- return LINK(iMaker->queryRoot());
- else
- return iMaker->create(NULL);
- }
- IPropertyTree *createPTree(IFileIO &ifileio, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
- {
- OwnedIFileIOStream stream = createIOStream(&ifileio);
- return createPTree(*stream, flags, readFlags, iMaker);
- }
- IPropertyTree *createPTree(IFile &ifile, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
- {
- OwnedIFileIO ifileio = ifile.open(IFOread);
- if (!ifileio)
- throw MakeStringException(0, "Could not locate filename: %s", ifile.queryFilename());
- return createPTree(*ifileio, flags, readFlags, iMaker);
- }
- IPropertyTree *createPTreeFromXMLFile(const char *filename, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
- {
- OwnedIFile ifile = createIFile(filename);
- return createPTree(*ifile, flags, readFlags, iMaker);
- }
- IPropertyTree *createPTreeFromXMLString(const char *xml, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
- {
- Owned<IPTreeMaker> _iMaker;
- if (!iMaker)
- {
- iMaker = createDefaultPTreeMaker(flags, readFlags);
- _iMaker.setown(iMaker);
- }
- Owned<IPTreeReader> reader = createXMLStringReader(xml, *iMaker, readFlags);
- reader->load();
- return LINK(iMaker->queryRoot());
- }
- IPropertyTree *createPTreeFromXMLString(unsigned len, const char *xml, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
- {
- Owned<IPTreeMaker> _iMaker;
- if (!iMaker)
- {
- iMaker = createDefaultPTreeMaker(flags, readFlags);
- _iMaker.setown(iMaker);
- }
- Owned<IPTreeReader> reader = createXMLBufferReader(xml, len, *iMaker, readFlags);
- reader->load();
- return LINK(iMaker->queryRoot());
- }
- //////////////////////////
- /////////////////////////
- static void _toXML(const IPropertyTree *tree, IIOStream &out, unsigned indent, unsigned flags)
- {
- const char *name = tree->queryName();
- if (!name) name = "__unnamed__";
- bool isBinary = tree->isBinary(NULL);
- bool inlinebody = true;
- if (flags & XML_Embed) writeCharsNToStream(out, ' ', indent);
- writeCharToStream(out, '<');
- writeStringToStream(out, name);
- Owned<IAttributeIterator> it = tree->getAttributes(true);
- if (it->first())
- {
- unsigned attributeindent = indent+2+(size32_t)strlen(name);
- bool first = true;
- do
- {
- const char *key = it->queryName();
- if (!isBinary || stricmp(key, "@xsi:type")!=0)
- {
- if (first)
- {
- if (flags & XML_LineBreak) inlinebody = false;
- first = false;
- writeCharToStream(out, ' ');
- }
- else if ((flags & XML_LineBreakAttributes) && it->count() > 3)
- {
- writeStringToStream(out, "\n");
- writeCharsNToStream(out, ' ', attributeindent);
- }
- else
- writeCharToStream(out, ' ');
- writeStringToStream(out, key+1);
- if (flags & XML_SingleQuoteAttributeValues)
- writeStringToStream(out, "='");
- else
- writeStringToStream(out, "=\"");
- const char *val = it->queryValue();
- if (val)
- {
- if (flags & XML_SanitizeAttributeValues)
- {
- 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)
- encodeXML(val, out, ENCODE_NEWLINES, (unsigned)-1, true);
- else
- {
- writeCharsNToStream(out, '*', strlen(val));
- }
- }
- else
- encodeXML(val, out, ENCODE_NEWLINES, (unsigned)-1, true);
- }
- if (flags & XML_SingleQuoteAttributeValues)
- writeCharToStream(out, '\'');
- else
- writeCharToStream(out, '"');
- }
- }
- while (it->next());
- }
- Owned<IPropertyTreeIterator> sub = tree->getElements("*", 0 != (flags & XML_SortTags) ? iptiter_sort : iptiter_null);
- MemoryBuffer thislevelbin;
- StringBuffer _thislevel;
- const char *thislevel = NULL; // to avoid uninitialized warning
- bool empty;
- if (isBinary)
- {
- if (flags & XML_LineBreak) inlinebody = false;
- writeStringToStream(out, " xsi:type=\"SOAP-ENC:base64\"");
- empty = (!tree->getPropBin(NULL, thislevelbin))||(thislevelbin.length()==0);
- }
- else
- {
- if (tree->isCompressed(NULL))
- {
- empty = false; // can't be empty if compressed;
- verifyex(tree->getProp(NULL, _thislevel));
- thislevel = _thislevel.str();
- }
- else
- empty = (NULL == (thislevel = tree->queryProp(NULL)));
- }
- if (sub->first())
- {
- if (flags & XML_LineBreak) inlinebody = false;
- }
- else if (empty && !(flags & XML_Sanitize))
- {
- if (flags & XML_LineBreak)
- writeStringToStream(out, "/>\n");
- else
- writeStringToStream(out, "/>");
- return;
- }
- writeCharToStream(out, '>');
- if (!inlinebody)
- writeStringToStream(out, "\n");
- for(; sub->isValid(); sub->next())
- _toXML(&sub->query(), out, indent+1, flags);
- if (!empty)
- {
- if (!inlinebody)
- writeCharsNToStream(out, ' ', indent+1);
- if (flags & XML_Sanitize)
- {
- // NOTE - we don't output anything for binary.... is that ok?
- if (thislevel)
- {
- 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)
- writeStringToStream(out, thislevel);
- else
- writeCharsNToStream(out, '*', strlen(thislevel));
- }
- }
- else if (isBinary)
- {
- if (flags & XML_NoBinaryEncode64)
- {
- if (flags & XML_NoEncode)
- {
- out.write(thislevelbin.length(), thislevelbin.toByteArray());
- }
- else
- {
- const char * buff = static_cast<const char *>(thislevelbin.toByteArray());
- const unsigned len = thislevelbin.length();
- unsigned prefix = 0;
- while ((prefix < len) && isspace(buff[prefix]))
- prefix++;
- encodeXML(buff, out, ENCODE_WHITESPACE, prefix, true);
- if (prefix != len) { // check not all spaces
- unsigned suffix = len;
- while (isspace(buff[suffix-1]))
- suffix--;
- encodeXML(buff+prefix, out, 0, suffix-prefix, true);
- encodeXML(buff+suffix, out, ENCODE_WHITESPACE, len-suffix, true);
- }
- }
- }
- else
- JBASE64_Encode(thislevelbin.toByteArray(), thislevelbin.length(), out);
- }
- else
- {
- if (flags & XML_NoEncode)
- {
- writeStringToStream(out, thislevel);
- }
- else
- {
- const char *m = thislevel;
- const char *p = m;
- while (isspace(*p))
- p++;
- encodeXML(m, out, ENCODE_WHITESPACE, p-m, true);
- if (*p) { // check not all spaces
- const char *s = p+strlen(p);
- while (isspace(*(s-1)))
- s--;
- assertex(s>p);
- encodeXML(p, out, 0, s-p, true);
- encodeXML(s, out, ENCODE_WHITESPACE, (unsigned)-1, true);
- }
- }
- if (!inlinebody)
- writeStringToStream(out, "\n");
- }
- }
- if (!inlinebody)
- writeCharsNToStream(out, ' ', indent);
- writeStringToStream(out, "</");
- writeStringToStream(out, name);
- if (flags & XML_LineBreak)
- writeStringToStream(out, ">\n");
- else
- writeCharToStream(out, '>');
- }
- jlib_decl StringBuffer &toXML(const IPropertyTree *tree, StringBuffer &ret, unsigned indent, unsigned flags)
- {
- class CAdapter : implements IIOStream, public CInterface
- {
- StringBuffer &out;
- public:
- IMPLEMENT_IINTERFACE;
- CAdapter(StringBuffer &_out) : out(_out) { }
- virtual void flush() override { }
- virtual size32_t read(size32_t len, void * data) override { UNIMPLEMENTED; return 0; }
- virtual size32_t write(size32_t len, const void * data) override { out.append(len, (const char *)data); return len; }
- } adapter(ret);
- _toXML(tree->queryBranch(NULL), adapter, indent, flags);
- return ret;
- }
- void toXML(const IPropertyTree *tree, IIOStream &out, unsigned indent, unsigned flags)
- {
- _toXML(tree, out, indent, flags);
- }
- void saveXML(const char *filename, const IPropertyTree *tree, unsigned indent, unsigned flags)
- {
- OwnedIFile ifile = createIFile(filename);
- saveXML(*ifile, tree, indent, flags);
- }
- void saveXML(IFile &ifile, const IPropertyTree *tree, unsigned indent, unsigned flags)
- {
- OwnedIFileIO ifileio = ifile.open(IFOcreate);
- if (!ifileio)
- throw MakeStringException(0, "saveXML: could not find %s to open", ifile.queryFilename());
- saveXML(*ifileio, tree, indent, flags);
- }
- void saveXML(IFileIO &ifileio, const IPropertyTree *tree, unsigned indent, unsigned flags)
- {
- Owned<IIOStream> stream = createIOStream(&ifileio);
- stream.setown(createBufferedIOStream(stream));
- saveXML(*stream, tree, indent, flags);
- }
- void saveXML(IIOStream &stream, const IPropertyTree *tree, unsigned indent, unsigned flags)
- {
- toXML(tree, stream, indent, flags);
- }
- /////////////////////////
- void checkWriteJSONDelimiter(IIOStream &out, bool &delimit)
- {
- if (delimit)
- writeCharToStream(out, ',');
- delimit = false;
- }
- static void writeJSONNameToStream(IIOStream &out, const char *name, unsigned indent, bool &delimit)
- {
- if (!name || !*name)
- return;
- checkWriteJSONDelimiter(out, delimit);
- if (indent)
- {
- writeCharToStream(out, '\n');
- writeCharsNToStream(out, ' ', indent);
- }
- else
- writeCharToStream(out, ' ');
- writeCharToStream(out, '"');
- writeStringToStream(out, name);
- writeStringToStream(out, "\": ");
- delimit = false;
- }
- static void writeJSONValueToStream(IIOStream &out, const char *val, bool &delimit, bool hidden=false)
- {
- checkWriteJSONDelimiter(out, delimit);
- delimit = true;
- if (!val)
- {
- writeStringToStream(out, "null");
- return;
- }
- writeCharToStream(out, '"');
- if (hidden)
- writeCharsNToStream(out, '*', strlen(val));
- else
- {
- StringBuffer s;
- writeStringToStream(out, encodeJSON(s, val));
- }
- writeCharToStream(out, '"');
- }
- static void writeJSONBase64ValueToStream(IIOStream &out, const char *val, size32_t len, bool &delimit)
- {
- checkWriteJSONDelimiter(out, delimit);
- delimit = true;
- if (!val)
- {
- writeStringToStream(out, "null");
- return;
- }
- writeCharToStream(out, '"');
- JBASE64_Encode(val, len, out);
- writeCharToStream(out, '"');
- }
- static void _toJSON(const IPropertyTree *tree, IIOStream &out, unsigned indent, byte flags, bool &delimit, bool root=false, bool isArrayItem=false)
- {
- Owned<IAttributeIterator> it = tree->getAttributes(true);
- bool hasAttributes = it->first();
- bool complex = (hasAttributes || tree->hasChildren());
- bool isBinary = tree->isBinary(NULL);
- const char *name = tree->queryName();
- if (!root && !isArrayItem)
- {
- if (!name || !*name)
- name = "__unnamed__";
- writeJSONNameToStream(out, name, (flags & JSON_Format) ? indent : 0, delimit);
- }
- checkWriteJSONDelimiter(out, delimit);
- if (isArrayItem && (flags & JSON_Format))
- {
- writeCharToStream(out, '\n');
- writeCharsNToStream(out, ' ', indent);
- }
- if (root || complex)
- {
- writeCharToStream(out, '{');
- delimit = false;
- }
- if (hasAttributes)
- {
- ForEach(*it)
- {
- const char *key = it->queryName();
- if (!isBinary || stricmp(key, "@xsi:type")!=0)
- {
- const char *val = it->queryValue();
- if (val)
- {
- writeJSONNameToStream(out, key, (flags & JSON_Format) ? indent+1 : 0, delimit);
- if (flags & JSON_SanitizeAttributeValues)
- {
- bool hide = !(streq(val, "0") || streq(val, "1") || strieq(val, "true") || strieq(val, "false") || strieq(val, "yes") || strieq(val, "no"));
- writeJSONValueToStream(out, val, delimit, hide);
- }
- else
- {
- StringBuffer encoded;
- encodeJSON(encoded, val);
- writeJSONValueToStream(out, encoded.str(), delimit);
- }
- }
- }
- }
- }
- MemoryBuffer thislevelbin;
- StringBuffer _thislevel;
- const char *thislevel = NULL; // to avoid uninitialized warning
- bool isNull;
- if (isBinary)
- {
- isNull = (!tree->getPropBin(NULL, thislevelbin))||(thislevelbin.length()==0);
- }
- else
- {
- if (tree->isCompressed(NULL))
- {
- isNull = false; // can't be empty if compressed;
- verifyex(tree->getProp(NULL, _thislevel));
- thislevel = _thislevel.str();
- }
- else
- isNull = (NULL == (thislevel = tree->queryProp(NULL)));
- }
- if (isNull && !root && !complex)
- {
- writeJSONValueToStream(out, NULL, delimit);
- return;
- }
- Owned<IPropertyTreeIterator> sub = tree->getElements("*", 0 != (flags & JSON_SortTags) ? iptiter_sort : iptiter_null);
- //note that detection of repeating elements relies on the fact that ptree elements
- //of the same name will be grouped together
- bool repeatingElement = false;
- sub->first();
- while(sub->isValid())
- {
- Linked<IPropertyTree> element = &sub->query();
- const char *name = element->queryName();
- if (sub->next() && !repeatingElement && streq(name, sub->query().queryName()))
- {
- if (flags & JSON_Format)
- indent++;
- writeJSONNameToStream(out, name, (flags & JSON_Format) ? indent : 0, delimit);
- writeCharToStream(out, '[');
- repeatingElement = true;
- delimit = false;
- }
- _toJSON(element, out, indent+1, flags, delimit, false, repeatingElement);
- if (repeatingElement && (!sub->isValid() || !streq(name, sub->query().queryName())))
- {
- if (flags & JSON_Format)
- {
- writeCharToStream(out, '\n');
- writeCharsNToStream(out, ' ', indent);
- indent--;
- }
- writeCharToStream(out, ']');
- repeatingElement = false;
- delimit = true;
- }
- }
- if (!isNull)
- {
- if (complex)
- writeJSONNameToStream(out, "#value", (flags & JSON_Format) ? indent+1 : 0, delimit);
- if (isBinary)
- writeJSONBase64ValueToStream(out, thislevelbin.toByteArray(), thislevelbin.length(), delimit);
- else
- {
- // NOTE - JSON_Sanitize won't output anything for binary.... is that ok?
- bool hide = (flags & JSON_Sanitize) && thislevel && !(streq(thislevel, "0") || streq(thislevel, "1") || strieq(thislevel, "true") || strieq(thislevel, "false") || strieq(thislevel, "yes") || strieq(thislevel, "no"));
- writeJSONValueToStream(out, thislevel, delimit, hide);
- }
- }
- if (root || complex)
- {
- if (flags & JSON_Format)
- {
- writeCharToStream(out, '\n');
- writeCharsNToStream(out, ' ', indent);
- }
- writeCharToStream(out, '}');
- delimit = true;
- }
- }
- jlib_decl StringBuffer &toJSON(const IPropertyTree *tree, StringBuffer &ret, unsigned indent, byte flags)
- {
- class CAdapter : implements IIOStream, public CInterface
- {
- StringBuffer &out;
- public:
- IMPLEMENT_IINTERFACE;
- CAdapter(StringBuffer &_out) : out(_out) { }
- virtual void flush() override { }
- virtual size32_t read(size32_t len, void * data) override { UNIMPLEMENTED; return 0; }
- virtual size32_t write(size32_t len, const void * data) override { out.append(len, (const char *)data); return len; }
- } adapter(ret);
- bool delimit = false;
- _toJSON(tree->queryBranch(NULL), adapter, indent, flags, delimit, true);
- return ret;
- }
- void toJSON(const IPropertyTree *tree, IIOStream &out, unsigned indent, byte flags)
- {
- bool delimit = false;
- _toJSON(tree, out, indent, flags, delimit, true);
- }
- static inline void skipWS(const char *&xpath)
- {
- while (isspace(*xpath)) xpath++;
- }
- static void _validateXPathSyntax(const char *xpath);
- static void validateQualifier(const char *&xxpath)
- {
- const char *xpath = xxpath;
- const char *start = xpath;
- skipWS(xpath);
- const char *lhsStart = xpath;
- for (;;)
- {
- switch (*xpath) {
- case ']':
- case '!':
- case '=':
- case '\0':
- break;
- default:
- if (!isspace(*xpath))
- {
- xpath++;
- continue;
- }
- }
- break;
- }
- StringAttr lhs(lhsStart, xpath-lhsStart);
- _validateXPathSyntax(lhs);
- skipWS(xpath);
- exprType tType = t_none;
- if ('=' == *xpath)
- {
- ++xpath;
- tType = t_equality;
- }
- else if ('!' == *xpath)
- {
- ++xpath;
- if (*xpath && '=' == *xpath)
- {
- tType = t_inequality;
- ++xpath;
- }
- else
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, 0, "Invalid qualifier expression");
- }
- if (t_none != tType)
- {
- skipWS(xpath);
- if ('~' == *xpath)
- {
- ++xpath; // Signifies wild (now always true but still accepted...)
- }
- skipWS(xpath);
- char qu = *xpath;
- if (qu != '\'' && qu != '\"')
- throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Syntax error - no opening \" or \'");
- ++xpath;
- while (*xpath && *xpath != qu)
- xpath++;
- if (!*xpath)
- throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Syntax error - no closing \" or \'");
- xpath++;
- }
- skipWS(xpath);
- if (']' != *xpath)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, 0, "No closing brace to qualifier");
- xxpath = xpath;
- }
- static void _validateXPathSyntax(const char *xpath)
- {
- if (NULL == xpath || '\0' == *xpath)
- return;
- else
- {
- const char *_xpath = xpath;
- restart:
- if (NULL == xpath || '\0' == *xpath)
- return;
- switch (*xpath)
- {
- case '.':
- ++xpath;
- goto restart;
- case '/':
- ++xpath;
- if ('/' == *xpath)
- {
- _validateXPathSyntax(xpath+1);
- return;
- }
- goto restart;
- case '[':
- {
- ++xpath;
- if (isdigit(*xpath))
- {
- StringAttr index;
- xpath = readIndex(xpath, index);
- unsigned i = atoi(index.get());
- if (i)
- {
- }
- else
- {
- // should be syntax error
- }
- if (']' != *xpath)
- throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
- }
- else
- validateQualifier(xpath);
- ++xpath;
- break;
- }
- default:
- {
- bool wild;
- const char *start = xpath;
- readWildId(xpath, wild); // validates also
- size32_t s = xpath-start;
- if (s)
- {
- StringAttr id(start, s);
- if ('[' == *xpath) // check for local index not iterative qualifier.
- {
- const char *xxpath = xpath+1;
- if (isdigit(*xxpath))
- {
- StringAttr idxstr;
- xxpath = readIndex(xxpath, idxstr);
- if (']' != *xxpath)
- throw MakeXPathException(_xpath, PTreeExcpt_XPath_ParseError, xpath-_xpath, "Qualifier brace unclosed");
- ++xxpath;
- unsigned index = atoi(idxstr.get());
- if (index)
- {
- }
- xpath = xxpath;
- }
- }
- }
- else if ('@' == *xpath)
- {
- ++xpath;
- const char *start = xpath;
- readID(xpath, false);
- size32_t s = xpath-start;
- if (!s)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Missing attribute?");
- StringAttr id(start, s);
- if (!validateXMLTag(id))
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Invalid xml tag: %s", id.get());
- while (isspace(*xpath)) xpath++;
- if ('\0' != *xpath)
- throw MakeXPathException(start, PTreeExcpt_XPath_ParseError, xpath-start, "Cannot have embedded attribute within path (must be tail component)");
- }
- else
- {
- if ('[' != *xpath)
- throw MakeXPathException(xpath, PTreeExcpt_XPath_ParseError, 0, "Qualifier expected e.g. [..]");
- validateQualifier(xpath);
- }
- break;
- }
- }
- }
- if (*xpath == '\0' || (*xpath == '/' && '\0' == *(xpath+1)))
- return;
- else
- _validateXPathSyntax(xpath);
- }
- bool validateXPathSyntax(const char *xpath, StringBuffer *error)
- {
- try
- {
- if (xpath && '/' == *xpath && *(xpath+1) != '/')
- throw MakeXPathException(xpath, PTreeExcpt_XPath_Unsupported, 0, "Root specifier \"/\" specifier is not supported");
- _validateXPathSyntax(xpath);
- return true;
- }
- catch (IException *e)
- {
- if (error)
- e->errorMessage(*error);
- e->Release();
- return false;
- }
- }
- static bool isContentXPath(const char *xpath, StringBuffer &head)
- {
- unsigned l = xpath?strlen(xpath):0;
- const char *x = xpath+l-2;
- if (l>=2 && 0==strcmp(XMLTAG_CONTENT, x))
- {
- if (x != xpath)
- head.append(x-xpath, xpath);
- return true;
- }
- return false;
- }
- bool validateXMLParseXPath(const char *xpath, StringBuffer *error)
- {
- if (!xpath || !*xpath)
- return true;
- StringBuffer head;
- if (isContentXPath(xpath, head))
- {
- if (head.length())
- {
- if ('/' == *xpath && '/' != *(xpath+1))
- {
- if (error)
- {
- Owned<IException> e = MakeStringException(0, "Invalid extract xml text '<>' usage, xpath cannot from be absolute: %s", xpath);
- e->errorMessage(*error);
- }
- return false;
- }
- return validateXPathSyntax(head.str(), error);
- }
- return true;
- }
- else
- return validateXPathSyntax('/' == *xpath && '/' != *(xpath+1) ? xpath+1 : xpath, error);
- return true;
- }
- bool areMatchingPTrees(IPropertyTree * left, IPropertyTree * right)
- {
- if (left == right)
- return true;
- if (!left || !right)
- return false;
- bool isCaseInsensitive = left->isCaseInsensitive();
- const char * lname = left->queryName();
- const char * rname = right->queryName();
- if (!lname || !rname)
- {
- if (lname || rname)
- return false;
- }
- else if ((isCaseInsensitive ? stricmp(lname, rname) : strcmp(lname, rname)) != 0)
- return false;
- Owned<IAttributeIterator> leftAttrIter = left->getAttributes(true);
- Owned<IAttributeIterator> rightAttrIter = right->getAttributes(true);
- rightAttrIter->first();
- ForEach(*leftAttrIter)
- {
- if (!rightAttrIter->isValid()) return false;
- const char * lname = leftAttrIter->queryName();
- const char * rname = rightAttrIter->queryName();
- if ((isCaseInsensitive ? stricmp(lname, rname) : strcmp(lname, rname)) != 0)
- return false;
- if (strcmp(leftAttrIter->queryValue(), rightAttrIter->queryValue()) != 0)
- return false;
- rightAttrIter->next();
- }
- if (rightAttrIter->isValid()) return false;
- Owned<IPropertyTreeIterator> leftElemIter = left->getElements("*", iptiter_sort);
- Owned<IPropertyTreeIterator> rightElemIter = right->getElements("*", iptiter_sort);
- rightElemIter->first();
- ForEach(*leftElemIter)
- {
- if (!rightElemIter->isValid()) return false;
- if (!areMatchingPTrees(&leftElemIter->query(), &rightElemIter->query()))
- return false;
- rightElemIter->next();
- }
- if (rightElemIter->isValid()) return false;
- return true;
- }
- /////////////////////
- static const char * skipWhitespace(const char * text)
- {
- while ((*text==' ') || (*text=='\t'))
- text++;
- return text;
- }
- static const char * skipAsterisk(const char * text)
- {
- if (*text=='*')
- return skipWhitespace(text+1);
- return text;
- }
- static const char * skipToNewline(const char * text)
- {
- while (*text && (*text != '\r') && (*text != '\n'))
- text++;
- return text;
- }
- static const char * skipNewline(const char * text)
- {
- if (*text == '\r')
- text++;
- if (*text == '\n')
- text++;
- return text;
- }
- void extractJavadoc(IPropertyTree * result, const char * text)
- {
- //Skip a leading blank line
- text = skipWhitespace(text);
- text = skipNewline(text);
- //Now process each of the parameters...
- StringBuffer tagname;
- StringBuffer tagtext;
- for (;;)
- {
- text = skipWhitespace(text);
- text = skipAsterisk(text);
- if ((*text == 0) || (*text == '@'))
- {
- if (tagtext.length())
- {
- if (tagname.length())
- result->addProp(tagname.str(), tagtext.str());
- else
- result->setProp("", tagtext.str());
- tagtext.clear();
- }
- if (*text == 0)
- return;
- text++;
- const char * start = text;
- while (isalnum(*text))
- text++;
- if (start != text)
- tagname.clear().append(text-start, start);
- text = skipWhitespace(text);
- }
- const char * start = text;
- text = skipToNewline(text);
- if (start != text)
- {
- if (tagtext.length())
- tagtext.append(" ");
- tagtext.append(text-start, start);
- }
- text = skipNewline(text);
- }
- }
- /////////////////////
- #ifdef _DEBUG
- jlib_decl void validatePTree()
- {
- Owned<IPropertyTree> testTree = createPTreeFromXMLString(
- "<ROOT>" \
- " <E a=\"av1\" b=\"bv1\" c=\"cv1\"></E>" \
- " <E a=\"av1\" b=\"bv1\" c=\"cv2\"></E>" \
- " <E a=\"av2\" b=\"bv1\"></E>" \
- " <SE c=\"cv1\"></SE>" \
- " <E a=\"av1\" b=\"bv2\"></E>" \
- " <E a=\"av2\" b=\"bv2\" c=\"cv3\">ev1</E>" \
- "</ROOT>"
- );
- Owned<IPropertyTreeIterator> iter = testTree->getElements("E[@a=\"av1\"][@b=\"bv2\"]");
- unsigned c = 0;
- ForEach (*iter)
- ++c;
- assertex(1 == c);
- int v = strcmp("bv1", testTree->queryProp("E[@a=\"av1\"][2]/@b"));
- assertex(0 == v);
- v = strcmp("cv2", testTree->queryProp("E[@a=\"av1\"][@b=\"bv1\"][2]/@c"));
- assertex(0 == v);
- v = strcmp("cv2", testTree->queryProp("E[@a=\"av1\"][2]/@c"));
- assertex(0 == v);
- v = strcmp("ev1", testTree->queryProp("E[@a=\"av2\"][@c]"));
- assertex(0 == v);
- }
- jlib_decl void testValidateXPathSyntax()
- {
- verifyex(validateXPathSyntax("@abc"));
- verifyex(validateXPathSyntax("prop"));
- verifyex(validateXPathSyntax("a/b"));
- verifyex(validateXPathSyntax("a/@b"));
- const char *s = "a[@a=\"blah\"]/b";
- verifyex(validateXPathSyntax(s));
- s = "a/b[@b=\"blah\"]";
- verifyex(validateXPathSyntax(s));
- verifyex(validateXPathSyntax(s));
- s = "a/b[b=\"blah\"]";
- verifyex(validateXPathSyntax(s));
- s = "a/b[a/b=\"blah\"]";
- verifyex(validateXPathSyntax(s));
- verifyex(validateXPathSyntax("a[1]/b[2]"));
- s = "a[b]/b[c=\"a\"]/c";
- verifyex(validateXPathSyntax(s));
- verifyex(validateXPathSyntax("//a/b/c"));
- verifyex(!validateXPathSyntax("a[b"));
- verifyex(!validateXPathSyntax("a["));
- verifyex(!validateXPathSyntax("a]"));
- verifyex(!validateXPathSyntax("a[b=blah]"));
- verifyex(!validateXPathSyntax("@a/b"));
- verifyex(!validateXPathSyntax("a[b[c]]"));
- verifyex(validateXMLParseXPath("<>"));
- verifyex(validateXMLParseXPath("a/b/c<>"));
- verifyex(validateXMLParseXPath("a/b/<>"));
- verifyex(validateXMLParseXPath("/a/b"));
- verifyex(!validateXMLParseXPath("a/b[\"]/<>"));
- verifyex(!validateXMLParseXPath("/<>"));
- }
- jlib_decl void testJdocCompare()
- {
- Owned<IPropertyTree> t1 = createPTree();
- Owned<IPropertyTree> t2 = createPTree();
- Owned<IPropertyTree> t3 = createPTree();
- Owned<IPropertyTree> t4 = createPTree();
- Owned<IPropertyTree> t5 = createPTree();
- extractJavadoc(t1, "Defines a record that contains information about a person");
- 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.");
- 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.");
- 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.");
- 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.");
- IPropertyTree * t2c = t2->addPropTree("Child1", createPTree());
- extractJavadoc(t2c, "This is some child data\n\n@param ages\tThe ages that are allowed to be processed.");
- IPropertyTree * t3c = t3->addPropTree("Child1", createPTree());
- extractJavadoc(t3c, "This is some child data\n\n@param ages\tThe ages that are allowed to be processed.");
- IPropertyTree * t4c = t4->addPropTree("Child1", createPTree());
- extractJavadoc(t4c, "This is some child data\n\n@param ages\tThe ages that are allowed to be processed, but differs.");
- IPropertyTree * t5c = t5->addPropTree("Child1", createPTree());
- extractJavadoc(t5c, "This is some child data\n\n@param ages\tThe ages that are allowed to be processed.");
- t2->setProp("@childAttr", "1");
- t3->setProp("@childAttr", "1");
- t4->setProp("@childAttr", "1");
- t5->setProp("@childAttr", "2");
- verifyex(areMatchingPTrees(NULL, NULL));
- verifyex(!areMatchingPTrees(NULL, t1));
- verifyex(!areMatchingPTrees(t1, NULL));
- verifyex(areMatchingPTrees(t1, t1));
- verifyex(areMatchingPTrees(t2, t3));
- verifyex(!areMatchingPTrees(t2, t4));
- verifyex(!areMatchingPTrees(t2, t5));
- }
- #endif
- template <class BASE_PTREE>
- class COrderedPTree : public BASE_PTREE
- {
- template <class BASECHILDMAP>
- class jlib_decl COrderedChildMap : public BASECHILDMAP
- {
- typedef COrderedChildMap<BASECHILDMAP> SELF;
- ICopyArrayOf<IPropertyTree> order;
- public:
- IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(IPropertyTree, constcharptr);
- COrderedChildMap<BASECHILDMAP>() : BASECHILDMAP() { }
- ~COrderedChildMap<BASECHILDMAP>() { SELF::kill(); }
- virtual unsigned numChildren() override { return order.ordinality(); }
- virtual IPropertyTreeIterator *getIterator(bool sort) override
- {
- class CPTArrayIterator : public ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>
- {
- IArrayOf<IPropertyTree> elems;
- public:
- CPTArrayIterator(ICopyArrayOf<IPropertyTree> &order, bool sort) : ArrayIIteratorOf<IArrayOf<IPropertyTree>, IPropertyTree, IPropertyTreeIterator>(elems)
- {
- ForEachItemIn(e, order)
- elems.append(*LINK(&order.item(e)));
- if (sort)
- elems.sort(comparePropTrees);
- }
- };
- return new CPTArrayIterator(order, sort);
- }
- virtual bool set(const char *key, IPropertyTree *tree) override
- {
- IPropertyTree *existing = find(*key);
- if (existing)
- {
- unsigned pos = order.find(*existing);
- BASECHILDMAP::set(key, tree);
- order.replace(*tree, pos);
- }
- else
- {
- BASECHILDMAP::set(key, tree);
- order.append(*tree);
- }
- return true;
- }
- virtual bool replace(const char *key, IPropertyTree *tree) override // provides different semantics, used if element being replaced is not to be treated as deleted.
- {
- return set(key, tree);
- }
- virtual bool remove(const char *key) override
- {
- IPropertyTree *child = BASECHILDMAP::find(*key);
- if (!child)
- return false;
- order.zap(*child);
- return BASECHILDMAP::removeExact(child);
- }
- virtual bool removeExact(IPropertyTree *child) override
- {
- order.zap(*child);
- return BASECHILDMAP::removeExact(child);
- }
- };
- public:
- typedef COrderedPTree<BASE_PTREE> SELF;
- COrderedPTree<BASE_PTREE>(const char *name=NULL, byte flags=ipt_none, IPTArrayValue *value=NULL, ChildMap *children=NULL)
- : BASE_PTREE(name, flags|ipt_ordered, value, children) { }
- virtual bool isEquivalent(IPropertyTree *tree) const override { return (NULL != QUERYINTERFACE(tree, COrderedPTree<BASE_PTREE>)); }
- virtual IPropertyTree *create(const char *name=NULL, IPTArrayValue *value=NULL, ChildMap *children=NULL, bool existing=false) override
- {
- return new COrderedPTree<BASE_PTREE>(name, SELF::flags, value, children);
- }
- virtual IPropertyTree *create(MemoryBuffer &mb) override
- {
- IPropertyTree *tree = new COrderedPTree<BASE_PTREE>();
- tree->deserialize(mb);
- return tree;
- }
- virtual void createChildMap() override
- {
- if (SELF::isnocase())
- SELF::children = new COrderedChildMap<ChildMapNC>();
- else
- SELF::children = new COrderedChildMap<ChildMap>();
- }
- };
- IPropertyTree *createPTree(byte flags)
- {
- return createPTree(NULL, flags);
- }
- IPropertyTree *createPTree(const char *name, byte flags)
- {
- switch (flags & (ipt_ordered|ipt_fast|ipt_lowmem))
- {
- case ipt_ordered|ipt_fast:
- return new COrderedPTree<LocalPTree>(name, flags);
- case ipt_ordered|ipt_lowmem:
- return new COrderedPTree<CAtomPTree>(name, flags);
- case ipt_ordered:
- return new COrderedPTree<DEFAULT_PTREE_TYPE>(name, flags);
- case ipt_fast:
- return new LocalPTree(name, flags);
- case ipt_lowmem:
- return new CAtomPTree(name, flags);
- case 0:
- return new DEFAULT_PTREE_TYPE(name, flags);
- default:
- throwUnexpectedX("Invalid flags - ipt_fast and ipt_lowmem should not be specified together");
- }
- }
- typedef enum _ptElementType
- {
- elementTypeUnknown,
- elementTypeNull,
- elementTypeString,
- elementTypeBool,
- elementTypeInteger,
- elementTypeReal,
- elementTypeObject,
- elementTypeArray
- } ptElementType;
- template <typename X>
- class CJSONReaderBase : public CommonReaderBase<X>
- {
- public:
- typedef CommonReaderBase<X> PARENT;
- using PARENT::reset;
- using PARENT::nextChar;
- using PARENT::readNextToken;
- using PARENT::checkReadNext;
- using PARENT::checkStartReadNext;
- using PARENT::readNext;
- using PARENT::expecting;
- using PARENT::match;
- using PARENT::error;
- using PARENT::skipWS;
- using PARENT::rewind;
- using PARENT::ignoreWhiteSpace;
- CJSONReaderBase(ISimpleReadStream &_stream, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions, size32_t _bufSize=0) :
- CommonReaderBase<X>(_stream, _iEvent, _readerOptions, _bufSize)
- {
- }
- CJSONReaderBase(const void *_buf, size32_t bufLength, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
- CommonReaderBase<X>(_buf, bufLength, _iEvent, _readerOptions)
- {
- }
- CJSONReaderBase(const void *_buf, IPTreeNotifyEvent &_iEvent, PTreeReaderOptions _readerOptions) :
- CommonReaderBase<X>(_buf, _iEvent, _readerOptions)
- {
- }
- ~CJSONReaderBase()
- {
- }
- protected:
- inline StringBuffer &appendChar(StringBuffer &id, char c)
- {
- int charlen = validJSONUtf8ChrLen(c);
- if (!charlen)
- error("invalid JSON character", true);
- id.append(nextChar);
- while (--charlen)
- {
- readNext();
- id.append(nextChar);
- }
- return id;
- }
- void readString(StringBuffer &value)
- {
- readNext();
- StringBuffer s;
- bool decode=false;
- while ('\"'!=nextChar)
- {
- if (nextChar=='\\')
- decode=true;
- appendChar(s, nextChar);
- readNext();
- }
- size32_t r = s.length();
- if (ignoreWhiteSpace)
- s.trimRight();
- if (decode)
- _decodeJSON(r, s.str(), value, s.length()+1);
- else
- value.swapWith(s);
- }
- void readName(StringBuffer &name)
- {
- if ('\"'!=nextChar)
- expecting("\"");
- readString(name);
- if (!name.length())
- error("empty JSON id");
- readNext();
- skipWS();
- if (':'!=nextChar)
- expecting(":");
- readNext();
- }
- ptElementType readValue(StringBuffer &value)
- {
- ptElementType type = elementTypeUnknown;
- switch (nextChar)
- {
- case '\"':
- {
- readString(value);
- type = elementTypeString;
- break;
- }
- case 't':
- match("rue", "Bad value");
- value.append("true");
- type = elementTypeBool;
- break;
- case 'f':
- match("alse", "Bad value");
- value.append("false");
- type = elementTypeBool;
- break;
- case 'n':
- match("ull", "Bad value");
- type = elementTypeNull;
- break;
- case '-':
- value.append(nextChar);
- readNext();
- //fall through
- default:
- if (!isdigit(nextChar))
- error("Bad value");
- type = elementTypeInteger;
- bool exponent = false;
- while (isdigit(nextChar) || '.'==nextChar || 'e'==nextChar || 'E'==nextChar)
- {
- if ('e'==nextChar || 'E'==nextChar)
- {
- if (exponent)
- error("Bad value");
- exponent=true;
- value.append(nextChar);
- readNext();
- if ('-'==nextChar)
- type=elementTypeReal;
- else if (!isdigit(nextChar) && '+'!=nextChar)
- error("Bad value");
- }
- if ('.'==nextChar)
- {
- if (exponent || type==elementTypeReal) //already found decimal
- error("Bad value");
- type = elementTypeReal;
- }
- value.append(nextChar);
- readNext();
- }
- rewind(1);
- break;
- }
- return type;
- }
- const char *_decodeJSON(unsigned read, const char *startMark, StringBuffer &ret, unsigned len)
- {
- const char *errMark = NULL;
- try { return decodeJSON(startMark, ret, len, &errMark); }
- catch (IException *e)
- {
- if (errMark)
- {
- if (read>(unsigned)(errMark-startMark))
- rewind((unsigned)(read - (errMark-startMark)));
- else
- rewind((unsigned)(errMark-startMark));
- }
- StringBuffer errMsg;
- e->errorMessage(errMsg);
- e->Release();
- error(errMsg.str());
- }
- return NULL; // will never get here.
- }
- };
- template <class X>
- class CJSONReader : public CJSONReaderBase<X>, implements IPTreeReader
- {
- typedef CJSONReaderBase<X> PARENT;
- using PARENT::checkBOM;
- using PARENT::rewind;
- using PARENT::readNext;
- using PARENT::readValue;
- using PARENT::readName;
- using PARENT::checkReadNext;
- using PARENT::checkSkipWS;
- using PARENT::checkStartReadNext;
- using PARENT::expecting;
- using PARENT::error;
- using PARENT::eos;
- using PARENT::_decodeJSON;
- using PARENT::skipWS;
- using PARENT::nextChar;
- using PARENT::curOffset;
- using PARENT::noRoot;
- using PARENT::ignoreWhiteSpace;
- using PARENT::iEvent;
- // StringBuffer tmpStr;
- public:
- IMPLEMENT_IINTERFACE;
- CJSONReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize=0)
- : PARENT(stream, iEvent, readerOptions, bufSize)
- {
- }
- CJSONReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
- : PARENT(buf, bufLength, iEvent, readerOptions)
- {
- }
- CJSONReader(const void *buf, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
- : PARENT(buf, iEvent, readerOptions)
- {
- }
- void readValueNotify(const char *name, bool skipAttributes)
- {
- offset_t startOffset = curOffset;
- StringBuffer value;
- if (readValue(value)==elementTypeNull)
- return;
- if ('@'==*name)
- {
- if (!skipAttributes)
- iEvent->newAttribute(name, value.str());
- return;
- }
- iEvent->beginNode(name, startOffset);
- iEvent->beginNodeContent(name);
- iEvent->endNode(name, value.length(), value.str(), false, curOffset);
- }
- void readArray(const char *name)
- {
- if ('@'==*name)
- name++;
- readNext();
- skipWS();
- while (']' != nextChar)
- {
- switch (nextChar)
- {
- case '[':
- iEvent->beginNode(name, curOffset);
- iEvent->beginNodeContent(name);
- readArray(name);
- iEvent->endNode(name, 0, "", false, curOffset);
- break;
- case '{':
- readObject(name);
- break;
- default:
- readValueNotify(name, true);
- break;
- }
- readNext();
- skipWS();
- if (','==nextChar)
- readNext();
- else if (']'!=nextChar)
- error("expected ',' or ']'");
- skipWS();
- }
- }
- void readChild(const char *name, bool skipAttributes)
- {
- skipWS();
- switch (nextChar)
- {
- case '}':
- {
- VStringBuffer msg("named item with no value defined %s [%d]", name, (int) curOffset);
- error(msg.str());
- }
- break;
- case '{':
- readObject(name);
- break;
- case '[':
- readArray(name);
- break;
- default:
- readValueNotify(name, skipAttributes);
- break;
- }
- }
- void readObject(const char *name)
- {
- if ('@'==*name)
- name++;
- iEvent->beginNode(name, curOffset);
- readNext();
- skipWS();
- bool attributesFinalized=false;
- while ('}' != nextChar)
- {
- StringBuffer tagName;
- readName(tagName);
- //internal convention so we can convert to and from xml
- //values at top of object with names starting with '@' become ptree attributes
- if (*tagName.str()!='@')
- attributesFinalized=true;
- readChild(tagName.str(), attributesFinalized);
- readNext();
- skipWS();
- if (','==nextChar)
- readNext();
- else if ('}'!=nextChar)
- error("expected ',' or '}'");
- skipWS();
- }
- iEvent->endNode(name, 0, "", false, curOffset);
- }
- void loadJSON()
- {
- if (!checkStartReadNext())
- return;
- if (checkBOM() && !checkReadNext())
- return;
- if (!checkSkipWS())
- return;
- if (noRoot)
- {
- StringBuffer tagName;
- for (;;)
- {
- switch (nextChar)
- {
- case '\"': //treat named objects like we're in a noroot object
- readName(tagName.clear());
- readChild(tagName.str(), true);
- break;
- case '{': //treat unnamed objects like we're in a noroot array
- readObject("__object__");
- break;
- case '[': //treat unnamed arrays like we're in a noroot array
- iEvent->beginNode("__array__", curOffset);
- readArray("__item__");
- iEvent->endNode("__array__", 0, "", false, curOffset);
- break;
- default:
- expecting("{[ or \"");
- }
- if (!checkReadNext() || !checkSkipWS())
- break;
- switch (nextChar)
- {
- case '{': //support file formats with whitespace (usually \n) seperated objects at the root
- case '[':
- break;
- case ',':
- readNext();
- skipWS();
- break;
- default:
- expecting(",");
- break;
- }
- }
- }
- else
- {
- if ('{' == nextChar)
- readObject("__object__");
- else if ('[' == nextChar)
- {
- iEvent->beginNode("__array__", curOffset);
- readArray("__item__");
- iEvent->endNode("__array__", 0, "", false, curOffset);
- }
- else
- error("expected '{' or '['");
- if (checkReadNext() && checkSkipWS())
- error("trailing content after JSON closed");
- }
- }
- // IPTreeReader
- virtual void load() { loadJSON(); }
- virtual offset_t queryOffset() { return curOffset; }
- };
- template <class X>
- class CPullJSONReader : public CJSONReaderBase<X>, implements IPullPTreeReader
- {
- typedef CJSONReaderBase<X> PARENT;
- using PARENT::checkBOM;
- using PARENT::rewind;
- using PARENT::readNext;
- using PARENT::readValue;
- using PARENT::readName;
- using PARENT::checkReadNext;
- using PARENT::checkSkipWS;
- using PARENT::checkStartReadNext;
- using PARENT::expecting;
- using PARENT::error;
- using PARENT::eos;
- using PARENT::_decodeJSON;
- using PARENT::skipWS;
- using PARENT::nextChar;
- using PARENT::curOffset;
- using PARENT::noRoot;
- using PARENT::ignoreWhiteSpace;
- using PARENT::iEvent;
- class CStateInfo : public CInterface
- {
- public:
- CStateInfo()
- {
- tag.ensureCapacity(15);
- type = elementTypeUnknown;
- childCount = 0;
- wnsTag = NULL;
- }
- inline void reset()
- {
- wnsTag = NULL;
- tag.clear();
- tagText.clear();
- type = elementTypeUnknown;
- childCount = 0;
- }
- StringBuffer tag;
- StringBuffer tagText;
- ptElementType type;
- const char *wnsTag;
- unsigned childCount;
- };
- CICopyArrayOf<CStateInfo> stack, freeStateInfo;
- CStateInfo *stateInfo;
- enum ParseStates { headerStart, nameStart, valueStart, itemStart, objAttributes, itemContent, itemEnd } state;
- bool endOfRoot;
- bool preReadItemName;
- bool more;
- StringBuffer tag, value;
- void init()
- {
- state = headerStart;
- stateInfo = NULL;
- endOfRoot = false;
- preReadItemName = false;
- more = true;
- }
- virtual void resetState()
- {
- stack.kill();
- more = true;
- }
- public:
- IMPLEMENT_IINTERFACE;
- CPullJSONReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize=0)
- : CJSONReaderBase<X>(stream, iEvent, readerOptions, bufSize)
- {
- init();
- }
- CPullJSONReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
- : CJSONReaderBase<X>(buf, bufLength, iEvent, readerOptions)
- {
- init();
- }
- CPullJSONReader(const void *buf, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
- : CJSONReaderBase<X>(buf, iEvent, readerOptions)
- {
- init();
- }
- ~CPullJSONReader()
- {
- ForEachItemIn(i, stack)
- delete &stack.item(i);
- ForEachItemIn(i2, freeStateInfo)
- delete &freeStateInfo.item(i2);
- }
- inline void checkDelimiter(const char *msg=",")
- {
- if (stateInfo && stateInfo->childCount > 0)
- {
- if (','!=nextChar)
- expecting(msg);
- readNext();
- skipWS();
- }
- }
- inline ptElementType getParentType()
- {
- if (stack.ordinality()<2)
- return stateInfo->type;
- return ((CStateInfo *)&stack.tos(1))->type;
- }
- void beginNode(const char *name, offset_t offset, ptElementType jsonType, bool notify=true)
- {
- if (stateInfo)
- stateInfo->childCount++;
- if (freeStateInfo.ordinality())
- {
- stateInfo = &freeStateInfo.popGet();
- stateInfo->reset();
- }
- else
- stateInfo = new CStateInfo;
- stack.append(*stateInfo);
- stateInfo->type=jsonType;
- if (name)
- stateInfo->tag.set(name);
- else
- stateInfo->tag.swapWith(tag);
- stateInfo->wnsTag = stateInfo->tag.str();
- if (!notify)
- return;
- try
- {
- iEvent->beginNode(stateInfo->wnsTag, offset);
- }
- catch (IPTreeException *pe)
- {
- if (PTreeExcpt_InvalidTagName == pe->errorCode())
- {
- pe->Release();
- StringBuffer msg("Expecting valid start tag, but got \"");
- error(msg.append(name).append("\"").str());
- }
- throw;
- }
- }
- inline const char *arrayItemName(const char *defaultName)
- {
- if (stack.ordinality()>1)
- return stateInfo->wnsTag;
- return defaultName;
- }
- bool arrayItem(offset_t offset)
- {
- skipWS();
- switch (nextChar)
- {
- case ']':
- state=itemContent;
- if (stack.ordinality()>1)
- readNext();
- if (!endNode(curOffset, getParentType()==elementTypeArray))
- return false;
- break;
- case '{':
- state=objAttributes;
- readNext();
- beginNode(arrayItemName("__object__"), offset, elementTypeObject);
- break;
- case '[':
- state=valueStart;
- readNext();
- beginNode(arrayItemName("__array__"), offset, elementTypeArray, true);
- break;
- default:
- state=valueStart;
- ptElementType type = readValue(value.clear());
- readNext();
- beginNode(arrayItemName("__item__"), offset, type, true);
- stateInfo->tagText.swapWith(value);
- break;
- }
- return true;
- }
- void namedItem()
- {
- if (!preReadItemName)
- readName(tag.clear());
- else
- preReadItemName = false;
- skipWS();
- switch (nextChar)
- {
- case '}':
- error("unexpected object close marker");
- case ']':
- error("unexpected array close marker");
- case '{':
- state=objAttributes;
- readNext();
- beginNode(NULL, curOffset, elementTypeObject);
- break;
- case '[':
- readNext();
- beginNode(NULL, curOffset, elementTypeArray, false); //false because items present events, not the array
- arrayItem(curOffset); //so process the first item so every next() has event
- break;
- default:
- state=valueStart;
- ptElementType type = readValue(value.clear());
- readNext();
- beginNode(NULL, curOffset, type);
- stateInfo->tagText.swapWith(value);
- break;
- }
- }
- void rootItem()
- {
- if ('\"'==nextChar)
- namedItem();
- else if ('{'==nextChar || '['==nextChar)
- arrayItem(curOffset);
- else
- expecting("[{ or \"");
- }
- bool rootNext()
- {
- if (!noRoot)
- return false;
- if (!checkReadNext() || !checkSkipWS())
- return true;
- switch (nextChar)
- {
- case '{': //support files where root level objects are separated by whitespace (usually \n)
- case '[':
- case ',':
- break;
- default:
- expecting(",");
- }
- return true;
- }
- void newNamedAttribute()
- {
- skipWS();
- readValue(value.clear());
- readNext();
- stateInfo->childCount++;
- iEvent->newAttribute(tag.str(), value.str());
- }
- bool endNode(offset_t offset, bool notify=true)
- {
- if (stack.ordinality()<2)
- {
- state = headerStart;
- more = rootNext();
- }
- if (notify)
- {
- if (stateInfo->type==elementTypeNull)
- iEvent->endNode(stateInfo->wnsTag, 0, "", false, offset);
- else
- iEvent->endNode(stateInfo->wnsTag, stateInfo->tagText.length(), stateInfo->tagText.str(), false, offset);
- }
- freeStateInfo.append(*stateInfo);
- stack.pop();
- stateInfo = (stack.ordinality()) ? &stack.tos() : NULL;
- return true;
- }
- // IPullPTreeReader
- virtual void load()
- {
- while (next()) {}
- }
- virtual void reset()
- {
- PARENT::reset();
- resetState();
- }
- virtual offset_t queryOffset() { return curOffset; }
- virtual bool next()
- {
- if (!more)
- return false;
- checkStartReadNext();
- checkSkipWS();
- switch (state)
- {
- case headerStart:
- {
- if (nextChar!='{' && nextChar!='[') //already positioned at start
- {
- if (!checkReadNext())
- return false;
- if (checkBOM())
- if (!checkReadNext())
- return false;
- if (!checkSkipWS())
- return false;
- }
- if (noRoot)
- rootItem();
- else
- {
- switch (nextChar)
- {
- case '{':
- state=objAttributes;
- readNext();
- beginNode("__object__", curOffset, elementTypeObject);
- break;
- case '[':
- state=valueStart;
- readNext();
- beginNode("__array__", curOffset, elementTypeArray);
- break;
- default:
- expecting("{ or [");
- break;
- }
- }
- break;
- }
- case nameStart:
- namedItem();
- break;
- case objAttributes:
- {
- if ('}'==nextChar)
- {
- state=itemEnd;
- iEvent->beginNodeContent(stateInfo->wnsTag);
- break;
- }
- checkDelimiter(", or }");
- if (nextChar != '\"')
- expecting("\"");
- readName(tag.clear());
- if (tag.charAt(0)=='@')
- newNamedAttribute();
- else
- {
- preReadItemName = true;
- state=itemContent;
- stateInfo->childCount=0;
- iEvent->beginNodeContent(stateInfo->wnsTag);
- }
- break;
- }
- case valueStart:
- state=itemContent;
- iEvent->beginNodeContent(stateInfo->wnsTag);
- break;
- case itemContent:
- {
- switch (stateInfo->type)
- {
- case elementTypeBool:
- case elementTypeString:
- case elementTypeInteger:
- case elementTypeReal:
- case elementTypeNull:
- return endNode(curOffset);
- break;
- case elementTypeArray:
- if (']'!=nextChar)
- checkDelimiter(", or ]");
- return arrayItem(curOffset);
- case elementTypeObject:
- if ('}'!=nextChar)
- {
- checkDelimiter(", or }");
- namedItem();
- }
- else
- {
- if (stack.ordinality()>1)
- readNext();
- return endNode(curOffset);
- }
- break;
- }
- break;
- }
- case itemEnd:
- {
- if (!stack.length())
- {
- if (!noRoot || !rootNext())
- return false;
- readNext();
- skipWS();
- rootItem();
- }
- else
- {
- readNext();
- state = itemContent;
- return endNode(curOffset);
- }
- break;
- }
- }
- return true;
- }
- };
- IPTreeReader *createJSONStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize)
- {
- class CJSONStreamReader : public CJSONReader<CInstStreamReader>
- {
- public:
- CJSONStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize=0) : CJSONReader<CInstStreamReader>(stream, iEvent, readerOptions, bufSize) { }
- };
- return new CJSONStreamReader(stream, iEvent, readerOptions, bufSize);
- }
- IPTreeReader *createJSONStringReader(const char *json, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
- {
- class CJSONStringReader : public CJSONReader<CInstStringReader>
- {
- public:
- CJSONStringReader(const void *json, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions) : CJSONReader<CInstStringReader>(json, iEvent, readerOptions) { }
- };
- if (NULL == json)
- throw createPTreeReadException(PTreeRead_syntax, "Null string passed to createJSONStringReader", NULL, 0, 0);
- return new CJSONStringReader(json, iEvent, readerOptions);
- }
- IPTreeReader *createJSONBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
- {
- class CJSONBufferReader : public CJSONReader<CInstBufferReader>
- {
- public:
- CJSONBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions) : CJSONReader<CInstBufferReader>(buf, bufLength, iEvent, readerOptions) { }
- };
- return new CJSONBufferReader(buf, bufLength, iEvent, readerOptions);
- }
- IPullPTreeReader *createPullJSONStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize)
- {
- class CJSONStreamReader : public CPullJSONReader<CInstStreamReader>
- {
- public:
- CJSONStreamReader(ISimpleReadStream &stream, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions, size32_t bufSize=0) : CPullJSONReader<CInstStreamReader>(stream, iEvent, readerOptions, bufSize) { }
- };
- return new CJSONStreamReader(stream, iEvent, readerOptions, bufSize);
- }
- IPullPTreeReader *createPullJSONStringReader(const char *json, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
- {
- class CJSONStringReader : public CPullJSONReader<CInstStringReader>
- {
- public:
- CJSONStringReader(const void *json, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions) : CPullJSONReader<CInstStringReader>(json, iEvent, readerOptions) { }
- };
- return new CJSONStringReader(json, iEvent, readerOptions);
- }
- IPullPTreeReader *createPullJSONBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions)
- {
- class CJSONBufferReader : public CPullJSONReader<CInstBufferReader>
- {
- public:
- CJSONBufferReader(const void *buf, size32_t bufLength, IPTreeNotifyEvent &iEvent, PTreeReaderOptions readerOptions) : CPullJSONReader<CInstBufferReader>(buf, bufLength, iEvent, readerOptions) { }
- };
- return new CJSONBufferReader(buf, bufLength, iEvent, readerOptions);
- }
- IPropertyTree *createPTreeFromJSONString(const char *json, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
- {
- Owned<IPTreeMaker> _iMaker;
- if (!iMaker)
- {
- iMaker = createDefaultPTreeMaker(flags, readFlags);
- _iMaker.setown(iMaker);
- }
- Owned<IPTreeReader> reader = createJSONStringReader(json, *iMaker, readFlags);
- reader->load();
- return LINK(iMaker->queryRoot());
- }
- IPropertyTree *createPTreeFromJSONString(unsigned len, const char *json, byte flags, PTreeReaderOptions readFlags, IPTreeMaker *iMaker)
- {
- Owned<IPTreeMaker> _iMaker;
- if (!iMaker)
- {
- iMaker = createDefaultPTreeMaker(flags, readFlags);
- _iMaker.setown(iMaker);
- }
- Owned<IPTreeReader> reader = createJSONBufferReader(json, len, *iMaker, readFlags);
- reader->load();
- return LINK(iMaker->queryRoot());
- }
- static const char * nextHttpParameterTag(StringBuffer &tag, const char *path)
- {
- while (*path=='.')
- path++;
- const char *finger = strchr(path, '.');
- if (finger)
- {
- tag.clear().append(finger - path, path);
- finger++;
- }
- else
- tag.set(path);
- return finger;
- }
- static void ensureHttpParameter(IPropertyTree *pt, StringBuffer &tag, const char *path, const char *value, const char *fullpath)
- {
- if (!tag.length())
- return;
- unsigned idx = 1;
- if (path && isdigit(*path))
- {
- StringBuffer pos;
- path = nextHttpParameterTag(pos, path);
- idx = (unsigned) atoi(pos.str())+1;
- }
- if (tag.charAt(tag.length()-1)=='$')
- {
- if (path && *path)
- throw MakeStringException(-1, "'$' not allowed in parent node of parameter path: %s", fullpath);
- tag.setLength(tag.length()-1);
- StringArray values;
- values.appendList(value, "\r");
- ForEachItemIn(pos, values)
- {
- const char *itemValue = values.item(pos);
- while (*itemValue=='\n')
- itemValue++;
- pt->addProp(tag, itemValue);
- }
- return;
- }
- unsigned count = pt->getCount(tag);
- while (count++ < idx)
- pt->addPropTree(tag, createPTree(tag));
- StringBuffer xpath(tag);
- xpath.append('[').append(idx).append(']');
- pt = pt->queryPropTree(xpath);
- if (!path || !*path)
- {
- pt->setProp(NULL, value);
- return;
- }
- StringBuffer nextTag;
- path = nextHttpParameterTag(nextTag, path);
- ensureHttpParameter(pt, nextTag, path, value, fullpath);
- }
- static void ensureHttpParameter(IPropertyTree *pt, const char *path, const char *value)
- {
- const char *fullpath = path;
- StringBuffer tag;
- path = nextHttpParameterTag(tag, path);
- ensureHttpParameter(pt, tag, path, value, fullpath);
- }
- bool checkParseUrlPathNodeValue(const char *s, StringBuffer &name, StringAttr &value)
- {
- s = skipWhitespace(s);
- const char *pn = strchr(s, '(');
- if (pn) //strict format param('value') so we can extend later
- {
- const char *vp = pn + 1;
- if (*vp!='\'')
- return false;
- const char *end =strchr(++vp, '\'');
- if (!end || *(end+1)!=')')
- return false;
- if (!validateXMLTag(name.append(pn-s, s).trim()))
- return false;
- value.set(vp, end-vp);
- }
- else
- {
- if (!validateXMLTag(name.append(s).trim()))
- return false;
- }
- return true;
- }
- IPropertyTree *createPTreeFromHttpPath(const char *nameWithAttrs, IPropertyTree *content, bool nestedRoot, ipt_flags flags)
- {
- StringArray nameAttrList;
- nameAttrList.appendList(nameWithAttrs, "/");
- if (!nameAttrList.ordinality())
- return NULL;
- Owned<IPropertyTree> pt = createPTree(nameAttrList.item(0), flags);
- for (aindex_t pos=1; nameAttrList.isItem(pos); pos++)
- {
- StringBuffer name;
- StringAttr value;
- if (!checkParseUrlPathNodeValue(nameAttrList.item(pos), name, value))
- throw MakeStringException(-1, "Invalid URL parameter format %s", nameAttrList.item(pos));
- StringBuffer xpath("@");
- xpath.append(name.str());
- if (!value.get())
- pt->setPropBool(xpath, true);
- else
- pt->setProp(xpath, value);
- }
- IPropertyTree *parent = pt;
- const char *input = pt->queryProp("@input");
- if (input)
- {
- StringArray inputNodes;
- inputNodes.appendList(input, ".");
- ForEachItemIn(in, inputNodes)
- {
- const char *tag = inputNodes.item(in);
- if (!validateXMLTag(tag))
- throw MakeStringException(-1, "Invalid REST query input specifier %s", input);
- parent = parent->addPropTree(tag, createPTree(tag, flags));
- }
- }
- if (streq("__array__", content->queryName()))
- {
- Owned<IAttributeIterator> aiter = content->getAttributes();
- ForEach (*aiter)
- parent->addProp(aiter->queryName(), aiter->queryValue());
- Owned<IPropertyTreeIterator> iter = content->getElements("__item__");
- ForEach (*iter)
- {
- IPropertyTree &e = iter->query();
- e.renameProp("/", "Row");
- parent->addPropTree("Row", LINK(&e));
- }
- }
- else
- mergePTree(parent, content);
- if (nestedRoot)
- {
- Owned<IPropertyTree> root = createPTree(flags);
- root->setPropTree(nameAttrList.item(0), pt.getClear());
- return root.getClear();
- }
- return pt.getClear();
- }
- //URL node nameWithAttrs is of the form: "TagName/attr1('abc')/attr2/attr3('xyz')"
- IPropertyTree *createPTreeFromHttpParameters(const char *nameWithAttrs, IProperties *parameters, bool skipLeadingDotParameters, bool nestedRoot, ipt_flags flags)
- {
- Owned<IPropertyTree> content = createPTree("content", flags);
- Owned<IPropertyIterator> iter = parameters->getIterator();
- ForEach(*iter)
- {
- StringBuffer key = iter->getPropKey();
- if (!key.length() || key.charAt(key.length()-1)=='!')
- continue;
- if (skipLeadingDotParameters && key.charAt(0)=='.')
- continue;
- const char *value = parameters->queryProp(key);
- if (!value || !*value)
- continue;
- ensureHttpParameter(content, key, value);
- }
- return createPTreeFromHttpPath(nameWithAttrs, content.getClear(), nestedRoot, flags);
- }
|