jptree.cpp 221 KB

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