jptree.cpp 214 KB

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