jptree.cpp 225 KB

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