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