jptree.cpp 219 KB

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