jptree.cpp 250 KB

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