ws_dfuService.cpp 207 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810
  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. #pragma warning (disable : 4786)
  14. #include <math.h>
  15. #include "daclient.hpp"
  16. #include "daft.hpp"
  17. #include "daftcfg.hpp"
  18. #include "fterror.hpp"
  19. #include "fverror.hpp"
  20. #include "daftprogress.hpp"
  21. #include "mpbase.hpp"
  22. #include "daclient.hpp"
  23. #include "dadfs.hpp"
  24. #include "dafdesc.hpp"
  25. #include "dasds.hpp"
  26. #include "danqs.hpp"
  27. #include "dalienv.hpp"
  28. #include "dautils.hpp"
  29. #include "jfile.hpp"
  30. #include "wshelpers.hpp"
  31. #include "LogicFileWrapper.hpp"
  32. #include "rmtfile.hpp"
  33. #include "dfuutil.hpp"
  34. #include "TpWrapper.hpp"
  35. #include "WUWrapper.hpp"
  36. #include "portlist.h"
  37. #include "roxiecommlib.hpp"
  38. #include "dfuwu.hpp"
  39. #include "fverror.hpp"
  40. #include "nbcd.hpp"
  41. #include "jstring.hpp"
  42. #include "exception_util.hpp"
  43. #include "ws_dfuService.hpp"
  44. #include "hqlerror.hpp"
  45. #include "hqlexpr.hpp"
  46. #include "hqlutil.hpp"
  47. #include "eclrtl.hpp"
  48. #include "package.h"
  49. #include "daaudit.hpp"
  50. #define Action_Delete "Delete"
  51. #define Action_AddtoSuperfile "Add To Superfile"
  52. static const char* FEATURE_URL="DfuAccess";
  53. #define FILE_NEWEST 1
  54. #define FILE_OLDEST 2
  55. #define FILE_LARGEST 3
  56. #define FILE_SMALLEST 4
  57. #define COUNTBY_SCOPE "Scope"
  58. #define COUNTBY_OWNER "Owner"
  59. #define COUNTBY_DATE "Date"
  60. #define COUNTBY_YEAR "Year"
  61. #define COUNTBY_QUARTER "Quarter"
  62. #define COUNTBY_MONTH "Month"
  63. #define COUNTBY_DAY "Day"
  64. #define REMOVE_FILE_SDS_CONNECT_TIMEOUT (1000*15) // 15 seconds
  65. const unsigned NODE_GROUP_CACHE_DEFAULT_TIMEOUT = 30*60*1000; //30 minutes
  66. const unsigned MAX_VIEWKEYFILE_ROWS = 1000;
  67. const unsigned MAX_KEY_ROWS = 20;
  68. short days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  69. CThorNodeGroup* CThorNodeGroupCache::readNodeGroup(const char* _groupName)
  70. {
  71. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  72. Owned<IConstEnvironment> env = factory->openEnvironment();
  73. Owned<IPropertyTree> root = &env->getPTree();
  74. Owned<IPropertyTreeIterator> it= root->getElements("Software/ThorCluster");
  75. ForEach(*it)
  76. {
  77. IPropertyTree& cluster = it->query();
  78. StringBuffer groupName;
  79. getClusterGroupName(cluster, groupName);
  80. if (groupName.length() && strieq(groupName.str(), _groupName))
  81. return new CThorNodeGroup(_groupName, cluster.getCount("ThorSlaveProcess"), cluster.getPropBool("@replicateOutputs", false));
  82. }
  83. return NULL;
  84. }
  85. CThorNodeGroup* CThorNodeGroupCache::lookup(const char* groupName, unsigned timeout)
  86. {
  87. CriticalBlock block(sect);
  88. CThorNodeGroup* item=SuperHashTableOf<CThorNodeGroup, const char>::find(groupName);
  89. if (item && !item->checkTimeout(timeout))
  90. return LINK(item);
  91. Owned<CThorNodeGroup> e = readNodeGroup(groupName);
  92. if (e)
  93. replace(*e.getLink()); //if not exists, will be added.
  94. return e.getClear();
  95. }
  96. void CWsDfuEx::init(IPropertyTree *cfg, const char *process, const char *service)
  97. {
  98. StringBuffer xpath;
  99. DBGLOG("Initializing %s service [process = %s]", service, process);
  100. espProcess.set(process);
  101. xpath.appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/DefaultScope", process, service);
  102. cfg->getProp(xpath.str(), defaultScope_);
  103. xpath.clear().appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/User", process, service);
  104. cfg->getProp(xpath.str(), user_);
  105. xpath.clear().appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/Password", process, service);
  106. cfg->getProp(xpath.str(), password_);
  107. StringBuffer disableUppercaseTranslation;
  108. xpath.clear().appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/DisableUppercaseTranslation", process, service);
  109. cfg->getProp(xpath.str(), disableUppercaseTranslation);
  110. m_clusterName.clear();
  111. xpath.clear().appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/ClusterName", process, service);
  112. cfg->getProp(xpath.str(), m_clusterName);
  113. Linked<IPropertyTree> globals;
  114. globals.set(cfg->queryPropTree(StringBuffer("Software/EspProcess[@name=\"").append(process).append("\"]/EspService[@name=\"").append(service).append("\"]").str()));
  115. const char * plugins = globals->queryProp("Plugins/@path");
  116. if (plugins)
  117. queryTransformerRegistry().addPlugins(plugins);
  118. m_disableUppercaseTranslation = false;
  119. if (streq(disableUppercaseTranslation.str(), "true"))
  120. m_disableUppercaseTranslation = true;
  121. xpath.setf("Software/EspProcess[@name=\"%s\"]/@PageCacheTimeoutSeconds", process);
  122. if (cfg->hasProp(xpath.str()))
  123. setPageCacheTimeoutMilliSeconds(cfg->getPropInt(xpath.str()));
  124. xpath.setf("Software/EspProcess[@name=\"%s\"]/@MaxPageCacheItems", process);
  125. if (cfg->hasProp(xpath.str()))
  126. setMaxPageCacheItems(cfg->getPropInt(xpath.str()));
  127. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/NodeGroupCacheMinutes", process, service);
  128. int timeout = cfg->getPropInt(xpath.str(), -1);
  129. if (timeout > -1)
  130. nodeGroupCacheTimeout = (unsigned) timeout*60*1000;
  131. else
  132. nodeGroupCacheTimeout = NODE_GROUP_CACHE_DEFAULT_TIMEOUT;
  133. thorNodeGroupCache.setown(new CThorNodeGroupCache());
  134. if (!daliClientActive())
  135. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
  136. setDaliServixSocketCaching(true);
  137. }
  138. bool CWsDfuEx::onDFUSearch(IEspContext &context, IEspDFUSearchRequest & req, IEspDFUSearchResponse & resp)
  139. {
  140. try
  141. {
  142. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  143. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to Search Logical Files. Permission denied.");
  144. StringBuffer username;
  145. context.getUserID(username);
  146. Owned<IUserDescriptor> userdesc;
  147. if(username.length() > 0)
  148. {
  149. userdesc.setown(createUserDescriptor());
  150. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  151. }
  152. CTpWrapper dummy;
  153. IArrayOf<IEspTpCluster> clusters;
  154. dummy.getClusterProcessList(eqThorCluster, clusters);
  155. dummy.getHthorClusterList(clusters);
  156. StringArray dfuclusters;
  157. ForEachItemIn(k, clusters)
  158. {
  159. IEspTpCluster& cluster = clusters.item(k);
  160. dfuclusters.append(cluster.getName());
  161. }
  162. IArrayOf<IEspTpCluster> clusters1;
  163. dummy.getClusterProcessList(eqRoxieCluster, clusters1);
  164. ForEachItemIn(k1, clusters1)
  165. {
  166. IEspTpCluster& cluster = clusters1.item(k1);
  167. StringBuffer slaveName = cluster.getName();
  168. dfuclusters.append(slaveName.str());
  169. }
  170. StringArray ftarray;
  171. ftarray.append("Logical Files and Superfiles");
  172. ftarray.append("Logical Files Only");
  173. ftarray.append("Superfiles Only");
  174. ftarray.append("Not in Superfiles");
  175. if (req.getShowExample() && *req.getShowExample())
  176. resp.setShowExample(req.getShowExample());
  177. resp.setClusterNames(dfuclusters);
  178. resp.setFileTypes(ftarray);
  179. }
  180. catch(IException* e)
  181. {
  182. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  183. }
  184. return true;
  185. }
  186. void addToQueryString(StringBuffer &queryString, const char *name, const char *value)
  187. {
  188. if (queryString.length() > 0)
  189. {
  190. queryString.append("&");
  191. }
  192. queryString.append(name);
  193. queryString.append("=");
  194. queryString.append(value);
  195. }
  196. void addToQueryStringFromInt(StringBuffer &queryString, const char *name, __int64 value)
  197. {
  198. if (queryString.length() > 0)
  199. {
  200. queryString.append("&");
  201. }
  202. queryString.append(name);
  203. queryString.append("=");
  204. queryString.append(value);
  205. }
  206. void parseTwoStringArrays(const char *input, StringArray& strarray1, StringArray& strarray2)
  207. {
  208. if (!input || strlen(input) <= 2)
  209. return;
  210. char c0[2], c1[2];
  211. c0[0] = input[0], c0[1] = 0;
  212. c1[0] = input[1], c1[1] = 0;
  213. //the first string usually is a name; the second is a value
  214. unsigned int name_len = atoi(c0);
  215. unsigned int value_len = atoi(c1);
  216. if (name_len > 0 && value_len > 0)
  217. {
  218. char * inputText = (char *) input;
  219. inputText += 2; //skip 2 chars
  220. for (;;)
  221. {
  222. if (!inputText || strlen(inputText) < name_len + value_len)
  223. break;
  224. StringBuffer columnNameLenStr, columnValueLenStr;
  225. for (unsigned i_name = 0; i_name < name_len; i_name++)
  226. {
  227. columnNameLenStr.append(inputText[0]);
  228. inputText++;
  229. }
  230. for (unsigned i_value = 0; i_value < value_len; i_value++)
  231. {
  232. columnValueLenStr.append(inputText[0]);
  233. inputText++;
  234. }
  235. unsigned columnNameLen = atoi(columnNameLenStr.str());
  236. unsigned columnValueLen = atoi(columnValueLenStr.str());
  237. if (!inputText || strlen(inputText) < columnNameLen + columnValueLen)
  238. break;
  239. char * colon = inputText + columnNameLen;
  240. if (!colon)
  241. break;
  242. StringAttr tmp;
  243. tmp.set(inputText, columnNameLen);
  244. strarray1.append(tmp.get());
  245. tmp.set(colon, columnValueLen);
  246. //tmp.toUpperCase();
  247. strarray2.append(tmp.get());
  248. inputText = colon + columnValueLen;
  249. }
  250. }
  251. return;
  252. }
  253. bool CWsDfuEx::onDFUQuery(IEspContext &context, IEspDFUQueryRequest & req, IEspDFUQueryResponse & resp)
  254. {
  255. try
  256. {
  257. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  258. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to Browse Logical Files. Permission denied.");
  259. StringBuffer username;
  260. context.getUserID(username);
  261. Owned<IUserDescriptor> userdesc;
  262. if(username.length() > 0)
  263. {
  264. userdesc.setown(createUserDescriptor());
  265. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  266. }
  267. doLogicalFileSearch(context, userdesc.get(), req, resp);
  268. }
  269. catch(IException* e)
  270. {
  271. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  272. }
  273. return true;
  274. }
  275. bool CWsDfuEx::onDFUInfo(IEspContext &context, IEspDFUInfoRequest &req, IEspDFUInfoResponse &resp)
  276. {
  277. try
  278. {
  279. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  280. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to access DFUInfo. Permission denied.");
  281. StringBuffer username;
  282. context.getUserID(username);
  283. Owned<IUserDescriptor> userdesc;
  284. if(username.length() > 0)
  285. {
  286. userdesc.setown(createUserDescriptor());
  287. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  288. }
  289. if (req.getUpdateDescription())
  290. {
  291. double version = context.getClientVersion();
  292. if (version < 1.38)
  293. doGetFileDetails(context, userdesc.get(), req.getFileName(), req.getCluster(), req.getQuerySet(), req.getQuery(), req.getFileDesc(),
  294. req.getIncludeJsonTypeInfo(), req.getIncludeBinTypeInfo(), req.getProtect(), resp.updateFileDetail());
  295. else
  296. doGetFileDetails(context, userdesc.get(), req.getName(), req.getCluster(), req.getQuerySet(), req.getQuery(), req.getFileDesc(),
  297. req.getIncludeJsonTypeInfo(), req.getIncludeBinTypeInfo(), req.getProtect(), resp.updateFileDetail());
  298. }
  299. else
  300. {
  301. doGetFileDetails(context, userdesc.get(), req.getName(), req.getCluster(), req.getQuerySet(), req.getQuery(), NULL,
  302. req.getIncludeJsonTypeInfo(), req.getIncludeBinTypeInfo(), req.getProtect(), resp.updateFileDetail());
  303. }
  304. }
  305. catch(IException* e)
  306. {
  307. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  308. }
  309. return true;
  310. }
  311. bool CWsDfuEx::onDFUSpace(IEspContext &context, IEspDFUSpaceRequest & req, IEspDFUSpaceResponse & resp)
  312. {
  313. try
  314. {
  315. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  316. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to Browse Space Usage. Permission denied.");
  317. StringBuffer username;
  318. context.getUserID(username);
  319. Owned<IUserDescriptor> userdesc;
  320. if(username.length() > 0)
  321. {
  322. userdesc.setown(createUserDescriptor());
  323. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  324. }
  325. const char *countby = req.getCountBy();
  326. if (!countby || strlen(countby) < 1)
  327. return true;
  328. char *scopeName = NULL;
  329. StringBuffer filter;
  330. if(req.getScopeUnder() && *req.getScopeUnder())
  331. {
  332. scopeName = (char *) req.getScopeUnder();
  333. filter.appendf("%s::*", scopeName);
  334. resp.setScopeUnder(req.getScopeUnder());
  335. }
  336. else
  337. {
  338. filter.append("*");
  339. }
  340. PROGLOG("DFUSpace: filter %s ", filter.str());
  341. Owned<IDFAttributesIterator> fi = queryDistributedFileDirectory().getDFAttributesIterator(filter, userdesc.get(), true, false, NULL);
  342. if(!fi)
  343. throw MakeStringException(ECLWATCH_CANNOT_GET_FILE_ITERATOR,"Cannot get information from file system.");
  344. const char *ownerUnder = NULL;
  345. if(req.getOwnerUnder() && *req.getOwnerUnder())
  346. {
  347. ownerUnder = req.getOwnerUnder();
  348. resp.setOwnerUnder(ownerUnder);
  349. }
  350. StringBuffer wuFrom, wuTo, interval;
  351. unsigned yearFrom = 0, monthFrom, dayFrom, yearTo = 0, monthTo, dayTo, hour, minute, second, nano;
  352. if(req.getStartDate() && *req.getStartDate())
  353. {
  354. CDateTime wuTime;
  355. wuTime.setString(req.getStartDate(),NULL,true);
  356. wuTime.getDate(yearFrom, monthFrom, dayFrom, true);
  357. wuTime.getTime(hour, minute, second, nano, true);
  358. wuFrom.appendf("%4d-%02d-%02d %02d:%02d:%02d",yearFrom,monthFrom,dayFrom,hour,minute,second);
  359. StringBuffer startDate;
  360. startDate.appendf("%02d/%02d/%04d", monthFrom, dayFrom, yearFrom);
  361. resp.setStartDate(startDate.str());
  362. }
  363. if(req.getEndDate() && *req.getEndDate())
  364. {
  365. CDateTime wuTime;
  366. wuTime.setString(req.getEndDate(),NULL,true);
  367. wuTime.getDate(yearTo, monthTo, dayTo, true);
  368. wuTime.getTime(hour, minute, second, nano, true);
  369. wuTo.appendf("%4d-%02d-%02d %02d:%02d:%02d",yearTo,monthTo,dayTo,hour,minute,second);
  370. StringBuffer endDate;
  371. endDate.appendf("%02d/%02d/%04d", monthTo, dayTo, yearTo);
  372. resp.setEndDate(endDate.str());
  373. }
  374. unsigned i = 0;
  375. IArrayOf<IEspSpaceItem> SpaceItems64;
  376. if (!stricmp(countby, COUNTBY_DATE))
  377. {
  378. if (yearFrom < 1 || yearTo < 1)
  379. {
  380. StringBuffer wuFrom, wuTo;
  381. bool bFirst = true;
  382. ForEach(*fi)
  383. {
  384. IPropertyTree &attr=fi->query();
  385. StringBuffer modf(attr.queryProp("@modified"));
  386. //char* t=strchr(modf.str(),'T');
  387. //if(t) *t=' ';
  388. if (bFirst)
  389. {
  390. bFirst = false;
  391. wuFrom = modf.str();
  392. wuTo = modf.str();
  393. continue;
  394. }
  395. if (strcmp(modf.str(),wuFrom.str())<0)
  396. wuFrom = modf.str();
  397. if (strcmp(modf.str(),wuTo.str())>0)
  398. wuTo = modf.str();
  399. }
  400. if (yearFrom < 1)
  401. {
  402. CDateTime wuTime;
  403. wuTime.setString(wuFrom.str(),NULL,true);
  404. wuTime.getDate(yearFrom, monthFrom, dayFrom, true);
  405. }
  406. if (yearTo < 1)
  407. {
  408. CDateTime wuTime;
  409. wuTime.setString(wuTo.str(),NULL,true);
  410. wuTime.getDate(yearTo, monthTo, dayTo, true);
  411. }
  412. }
  413. interval = req.getInterval();
  414. resp.setInterval(interval);
  415. createSpaceItemsByDate(SpaceItems64, interval, yearFrom, monthFrom, dayFrom, yearTo, monthTo, dayTo);
  416. }
  417. else
  418. {
  419. Owned<IEspSpaceItem> item64 = createSpaceItem();
  420. if (stricmp(countby, COUNTBY_OWNER))
  421. {
  422. if (scopeName)
  423. item64->setName(scopeName);
  424. else
  425. item64->setName("(root)");
  426. }
  427. else
  428. {
  429. item64->setName("(empty)");
  430. }
  431. item64->setNumOfFilesInt(0);
  432. item64->setNumOfFilesIntUnknown(0);
  433. item64->setTotalSizeInt(0);
  434. item64->setLargestSizeInt(0);
  435. item64->setSmallestSizeInt(0);
  436. item64->setLargestFile("");
  437. item64->setSmallestFile("");
  438. SpaceItems64.append(*item64.getClear());
  439. }
  440. ForEach(*fi)
  441. {
  442. IPropertyTree &attr=fi->query();
  443. if (attr.hasProp("@numsubfiles"))
  444. continue; //exclude superfiles
  445. if (ownerUnder)
  446. {
  447. const char* owner=attr.queryProp("@owner");
  448. if (owner && stricmp(owner, ownerUnder))
  449. continue;
  450. }
  451. StringBuffer modf(attr.queryProp("@modified"));
  452. char* t= (char *) strchr(modf.str(),'T');
  453. if(t) *t=' ';
  454. if (wuFrom.length() && strcmp(modf.str(),wuFrom.str())<0)
  455. continue;
  456. if (wuTo.length() && strcmp(modf.str(),wuTo.str())>0)
  457. continue;
  458. if (!stricmp(countby, COUNTBY_DATE))
  459. {
  460. setSpaceItemByDate(SpaceItems64, interval, attr.queryProp("@modified"), attr.queryProp("@name"), attr.getPropInt64("@size",-1));
  461. }
  462. else if (!stricmp(countby, COUNTBY_OWNER))
  463. {
  464. setSpaceItemByOwner(SpaceItems64, attr.queryProp("@owner"), attr.queryProp("@name"), attr.getPropInt64("@size",-1));
  465. }
  466. else
  467. {
  468. setSpaceItemByScope(SpaceItems64, scopeName, attr.queryProp("@name"), attr.getPropInt64("@size",-1));
  469. }
  470. }
  471. i = 0;
  472. IEspSpaceItem& item0 = SpaceItems64.item(0);
  473. if (item0.getNumOfFilesInt() < 1)
  474. {
  475. i++;
  476. }
  477. double version = context.getClientVersion();
  478. IArrayOf<IEspDFUSpaceItem> SpaceItems;
  479. for(; i < SpaceItems64.length();i++)
  480. {
  481. IEspSpaceItem& item64 = SpaceItems64.item(i);
  482. if (item64.getNumOfFilesInt() < 1)
  483. continue;
  484. StringBuffer buf;
  485. Owned<IEspDFUSpaceItem> item1 = createDFUSpaceItem("","");
  486. __int64 numOfFiles = item64.getNumOfFilesInt();
  487. __int64 numOfFilesIntUnknown = item64.getNumOfFilesIntUnknown();
  488. __int64 totalSize = item64.getTotalSizeInt();
  489. __int64 largestSize = item64.getLargestSizeInt();
  490. __int64 smallestSize = item64.getSmallestSizeInt();
  491. if (version >= 1.38)
  492. {
  493. item1->setNumOfFilesInt64(numOfFiles);
  494. item1->setNumOfFilesUnknownInt64(numOfFilesIntUnknown);
  495. item1->setTotalSizeInt64(totalSize);
  496. item1->setLargestSizeInt64(largestSize);
  497. item1->setSmallestSizeInt64(smallestSize);
  498. }
  499. item1->setName(item64.getName());
  500. buf << comma(numOfFiles);
  501. item1->setNumOfFiles(buf.str());
  502. buf.clear();
  503. buf << comma(numOfFilesIntUnknown);
  504. item1->setNumOfFilesUnknown(buf.str());
  505. buf.clear();
  506. buf << comma(totalSize);
  507. item1->setTotalSize(buf.str());
  508. buf.clear();
  509. buf << comma(largestSize);
  510. item1->setLargestSize(buf.str());
  511. buf.clear();
  512. buf << comma(smallestSize);
  513. item1->setSmallestSize(buf.str());
  514. item1->setLargestFile(item64.getLargestFile());
  515. item1->setSmallestFile(item64.getSmallestFile());
  516. SpaceItems.append(*item1.getClear());
  517. }
  518. resp.setDFUSpaceItems(SpaceItems);
  519. resp.setCountBy(req.getCountBy());
  520. }
  521. catch(IException* e)
  522. {
  523. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  524. }
  525. return true;
  526. }
  527. bool CWsDfuEx::setSpaceItemByScope(IArrayOf<IEspSpaceItem>& SpaceItems64, const char*scopeName, const char*logicalName, __int64 size)
  528. {
  529. char scope[1024];
  530. scope[0] = 0;
  531. const char* pName = NULL;
  532. if (!scopeName)
  533. {
  534. pName = strstr(logicalName, "::");
  535. if (!pName)
  536. return false;
  537. strncpy(scope, logicalName, pName - logicalName);
  538. scope[pName - logicalName] = 0;
  539. }
  540. else
  541. {
  542. if (strlen(logicalName) <= strlen(scopeName)+2)
  543. return false;
  544. char* ppName = (char*) logicalName + strlen(scopeName) + 2;
  545. pName = strstr(ppName, "::");
  546. if (pName)
  547. {
  548. strncpy(scope, logicalName, pName - logicalName);
  549. scope[pName - logicalName] = 0;
  550. }
  551. }
  552. if (strlen(scope) > 0)
  553. {
  554. IEspSpaceItem *item0 = NULL;
  555. for(unsigned i = 0; i < SpaceItems64.length();i++)
  556. {
  557. IEspSpaceItem& item1 = SpaceItems64.item(i);
  558. if (!stricmp(item1.getName(), scope))
  559. {
  560. item0 = &item1;
  561. break;
  562. }
  563. }
  564. if (!item0)
  565. {
  566. Owned<IEspSpaceItem> item1 = createSpaceItem();
  567. item1->setName(scope);
  568. item1->setNumOfFilesInt(1);
  569. if (size < 0)
  570. {
  571. item1->setNumOfFilesIntUnknown(1);
  572. item1->setTotalSizeInt(0);
  573. item1->setLargestSizeInt(0);
  574. item1->setSmallestSizeInt(0);
  575. item1->setLargestFile("");
  576. item1->setSmallestFile("");
  577. }
  578. else
  579. {
  580. item1->setNumOfFilesIntUnknown(0);
  581. item1->setTotalSizeInt(size);
  582. item1->setLargestSizeInt(size);
  583. item1->setSmallestSizeInt(size);
  584. item1->setLargestFile(logicalName);
  585. item1->setSmallestFile(logicalName);
  586. }
  587. SpaceItems64.append(*item1.getClear());
  588. }
  589. else if (size < 0)
  590. {
  591. item0->setNumOfFilesIntUnknown(item0->getNumOfFilesIntUnknown() + 1);
  592. item0->setNumOfFilesInt(item0->getNumOfFilesInt() + 1);
  593. }
  594. else
  595. {
  596. if (item0->getNumOfFilesInt() == item0->getNumOfFilesIntUnknown() || size > item0->getLargestSizeInt())
  597. {
  598. item0->setLargestSizeInt(size);
  599. item0->setLargestFile(logicalName);
  600. }
  601. if (item0->getNumOfFilesInt() == item0->getNumOfFilesIntUnknown() || size < item0->getSmallestSizeInt())
  602. {
  603. item0->setSmallestSizeInt(size);
  604. item0->setSmallestFile(logicalName);
  605. }
  606. item0->setNumOfFilesInt(item0->getNumOfFilesInt() + 1);
  607. item0->setTotalSizeInt(item0->getTotalSizeInt() + size);
  608. }
  609. }
  610. else
  611. {
  612. IEspSpaceItem& item0 = SpaceItems64.item(0);
  613. if (size < 0)
  614. {
  615. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  616. item0.setNumOfFilesIntUnknown(item0.getNumOfFilesIntUnknown() + 1);
  617. }
  618. else
  619. {
  620. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size > item0.getLargestSizeInt()))
  621. {
  622. item0.setLargestSizeInt(size);
  623. item0.setLargestFile(logicalName);
  624. }
  625. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size < item0.getSmallestSizeInt()))
  626. {
  627. item0.setSmallestSizeInt(size);
  628. item0.setSmallestFile(logicalName);
  629. }
  630. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  631. item0.setTotalSizeInt(item0.getTotalSizeInt() + size);
  632. }
  633. }
  634. return true;
  635. }
  636. bool CWsDfuEx::setSpaceItemByOwner(IArrayOf<IEspSpaceItem>& SpaceItems64, const char *owner, const char *logicalName, __int64 size)
  637. {
  638. if (owner && *owner)
  639. {
  640. IEspSpaceItem *item0 = NULL;
  641. for(unsigned i = 0; i < SpaceItems64.length();i++)
  642. {
  643. IEspSpaceItem& item1 = SpaceItems64.item(i);
  644. if (!stricmp(item1.getName(), owner))
  645. {
  646. item0 = &item1;
  647. break;
  648. }
  649. }
  650. if (!item0)
  651. {
  652. Owned<IEspSpaceItem> item1 = createSpaceItem();
  653. item1->setName(owner);
  654. item1->setNumOfFilesInt(1);
  655. if (size < 0)
  656. {
  657. item1->setNumOfFilesIntUnknown(1);
  658. item1->setTotalSizeInt(0);
  659. item1->setLargestSizeInt(0);
  660. item1->setSmallestSizeInt(0);
  661. item1->setLargestFile("");
  662. item1->setSmallestFile("");
  663. }
  664. else
  665. {
  666. item1->setNumOfFilesIntUnknown(0);
  667. item1->setTotalSizeInt(size);
  668. item1->setLargestSizeInt(size);
  669. item1->setSmallestSizeInt(size);
  670. item1->setLargestFile(logicalName);
  671. item1->setSmallestFile(logicalName);
  672. }
  673. SpaceItems64.append(*item1.getClear());
  674. }
  675. else if (size < 0)
  676. {
  677. item0->setNumOfFilesIntUnknown(item0->getNumOfFilesIntUnknown() + 1);
  678. item0->setNumOfFilesInt(item0->getNumOfFilesInt() + 1);
  679. }
  680. else
  681. {
  682. if (item0->getNumOfFilesInt() == item0->getNumOfFilesIntUnknown() || size > item0->getLargestSizeInt())
  683. {
  684. item0->setLargestSizeInt(size);
  685. item0->setLargestFile(logicalName);
  686. }
  687. if (item0->getNumOfFilesInt() == item0->getNumOfFilesIntUnknown() || size < item0->getSmallestSizeInt())
  688. {
  689. item0->setSmallestSizeInt(size);
  690. item0->setSmallestFile(logicalName);
  691. }
  692. item0->setNumOfFilesInt(item0->getNumOfFilesInt() + 1);
  693. item0->setTotalSizeInt(item0->getTotalSizeInt() + size);
  694. }
  695. }
  696. else
  697. {
  698. IEspSpaceItem& item0 = SpaceItems64.item(0);
  699. if (size < 0)
  700. {
  701. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  702. item0.setNumOfFilesIntUnknown(item0.getNumOfFilesIntUnknown() + 1);
  703. }
  704. else
  705. {
  706. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size > item0.getLargestSizeInt()))
  707. {
  708. item0.setLargestSizeInt(size);
  709. item0.setLargestFile(logicalName);
  710. }
  711. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size < item0.getSmallestSizeInt()))
  712. {
  713. item0.setSmallestSizeInt(size);
  714. item0.setSmallestFile(logicalName);
  715. }
  716. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  717. item0.setTotalSizeInt(item0.getTotalSizeInt() + size);
  718. }
  719. }
  720. return true;
  721. }
  722. bool CWsDfuEx::createSpaceItemsByDate(IArrayOf<IEspSpaceItem>& SpaceItems, StringBuffer interval, unsigned& yearFrom,
  723. unsigned& monthFrom, unsigned& dayFrom, unsigned& yearTo, unsigned& monthTo, unsigned& dayTo)
  724. {
  725. if (!stricmp(interval, COUNTBY_YEAR))
  726. {
  727. for (unsigned i = yearFrom; i <= yearTo; i++)
  728. {
  729. Owned<IEspSpaceItem> item64 = createSpaceItem();
  730. StringBuffer name;
  731. name.appendf("%04d", i);
  732. item64->setName(name.str());
  733. item64->setNumOfFilesInt(0);
  734. item64->setNumOfFilesIntUnknown(0);
  735. item64->setTotalSizeInt(0);
  736. item64->setLargestSizeInt(0);
  737. item64->setSmallestSizeInt(0);
  738. item64->setLargestFile("");
  739. item64->setSmallestFile("");
  740. SpaceItems.append(*item64.getClear());
  741. }
  742. }
  743. else if (!stricmp(interval, COUNTBY_QUARTER))
  744. {
  745. for (unsigned i = yearFrom; i <= yearTo; i++)
  746. {
  747. int quartStart = 1;
  748. int quartEnd = 4;
  749. if (i == yearFrom)
  750. {
  751. if (monthFrom > 9)
  752. {
  753. quartStart = 4;
  754. }
  755. else if (monthFrom > 6)
  756. {
  757. quartStart = 3;
  758. }
  759. else if (monthFrom > 3)
  760. {
  761. quartStart = 2;
  762. }
  763. }
  764. if (i == yearTo)
  765. {
  766. if (monthTo > 9)
  767. {
  768. quartEnd = 4;
  769. }
  770. else if (monthTo > 6)
  771. {
  772. quartEnd = 3;
  773. }
  774. else if (monthTo > 3)
  775. {
  776. quartEnd = 2;
  777. }
  778. }
  779. for (int j = quartStart; j <= quartEnd; j++)
  780. {
  781. Owned<IEspSpaceItem> item64 = createSpaceItem();
  782. StringBuffer name;
  783. name.appendf("%04d quarter: %d", i, j);
  784. item64->setName(name.str());
  785. item64->setNumOfFilesInt(0);
  786. item64->setNumOfFilesIntUnknown(0);
  787. item64->setTotalSizeInt(0);
  788. item64->setLargestSizeInt(0);
  789. item64->setSmallestSizeInt(0);
  790. item64->setLargestFile("");
  791. item64->setSmallestFile("");
  792. SpaceItems.append(*item64.getClear());
  793. }
  794. }
  795. }
  796. else if (!stricmp(interval, COUNTBY_MONTH))
  797. {
  798. for (unsigned i = yearFrom; i <= yearTo; i++)
  799. {
  800. int jFrom = (i != yearFrom) ? 1 : monthFrom;
  801. int jTo = (i != yearTo) ? 12 : monthTo;
  802. for (int j = jFrom; j <= jTo; j++)
  803. {
  804. Owned<IEspSpaceItem> item64 = createSpaceItem();
  805. StringBuffer name;
  806. name.appendf("%04d-%02d", i, j);
  807. item64->setName(name.str());
  808. item64->setNumOfFilesInt(0);
  809. item64->setNumOfFilesIntUnknown(0);
  810. item64->setTotalSizeInt(0);
  811. item64->setLargestSizeInt(0);
  812. item64->setSmallestSizeInt(0);
  813. item64->setLargestFile("");
  814. item64->setSmallestFile("");
  815. SpaceItems.append(*item64.getClear());
  816. }
  817. }
  818. }
  819. else
  820. {
  821. for (unsigned i = yearFrom; i <= yearTo; i++)
  822. {
  823. int jFrom = (i != yearFrom) ? 1 : monthFrom;
  824. int jTo = (i != yearTo) ? 12 : monthTo;
  825. for (int j = jFrom; j <= jTo; j++)
  826. {
  827. int dayStart = 1;
  828. int dayEnd = days[j-1];
  829. if (i == yearFrom && j == monthFrom)
  830. {
  831. dayStart = dayFrom;
  832. }
  833. else if (i == yearTo && j == monthTo)
  834. {
  835. dayEnd = dayTo;
  836. }
  837. for (int k = dayStart; k <= dayEnd; k++)
  838. {
  839. Owned<IEspSpaceItem> item64 = createSpaceItem();
  840. StringBuffer name;
  841. name.appendf("%04d-%02d-%02d", i, j, k);
  842. item64->setName(name.str());
  843. item64->setNumOfFilesInt(0);
  844. item64->setNumOfFilesIntUnknown(0);
  845. item64->setTotalSizeInt(0);
  846. item64->setLargestSizeInt(0);
  847. item64->setSmallestSizeInt(0);
  848. item64->setLargestFile("");
  849. item64->setSmallestFile("");
  850. SpaceItems.append(*item64.getClear());
  851. }
  852. }
  853. }
  854. }
  855. return true;
  856. }
  857. bool CWsDfuEx::setSpaceItemByDate(IArrayOf<IEspSpaceItem>& SpaceItems, StringBuffer interval, StringBuffer mod, const char*logicalName, __int64 size)
  858. {
  859. unsigned year, month, day;
  860. CDateTime wuTime;
  861. wuTime.setString(mod.str(),NULL,true);
  862. wuTime.getDate(year, month, day, true);
  863. StringBuffer name;
  864. if (!stricmp(interval, COUNTBY_YEAR))
  865. {
  866. name.appendf("%04d", year);
  867. }
  868. else if (!stricmp(interval, COUNTBY_QUARTER))
  869. {
  870. int quart = 1;
  871. if (month > 9)
  872. {
  873. quart = 4;
  874. }
  875. else if (month > 6)
  876. {
  877. quart = 3;
  878. }
  879. else if (month > 3)
  880. {
  881. quart = 2;
  882. }
  883. name.appendf("%04d quarter: %d", year, quart);
  884. }
  885. else if (!stricmp(interval, COUNTBY_MONTH))
  886. {
  887. name.appendf("%04d-%02d", year, month);
  888. }
  889. else
  890. {
  891. name.appendf("%04d-%02d-%02d", year, month, day);
  892. }
  893. for (unsigned i = 0; i < SpaceItems.length(); i++)
  894. {
  895. IEspSpaceItem& item0 = SpaceItems.item(i);
  896. if (!stricmp(item0.getName(), name))
  897. {
  898. if (size < 0)
  899. {
  900. item0.setNumOfFilesIntUnknown(item0.getNumOfFilesIntUnknown() + 1);
  901. }
  902. else
  903. {
  904. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size > item0.getLargestSizeInt()))
  905. {
  906. item0.setLargestSizeInt(size);
  907. item0.setLargestFile(logicalName);
  908. }
  909. if ((item0.getNumOfFilesInt() == item0.getNumOfFilesIntUnknown()) || (size < item0.getSmallestSizeInt()))
  910. {
  911. item0.setSmallestSizeInt(size);
  912. item0.setSmallestFile(logicalName);
  913. }
  914. item0.setTotalSizeInt(item0.getTotalSizeInt() + size);
  915. }
  916. item0.setNumOfFilesInt(item0.getNumOfFilesInt() + 1);
  917. break;
  918. }
  919. }
  920. return true;
  921. }
  922. void CWsDfuEx::parseStringArray(const char *input, StringArray& strarray)
  923. {
  924. if (!input || !*input)
  925. return;
  926. const char *ptr = input;
  927. const char *pptr = ptr;
  928. while (pptr[0])
  929. {
  930. if (pptr[0] == ',')
  931. {
  932. StringAttr tmp;
  933. tmp.set(ptr, pptr-ptr);
  934. strarray.append(tmp.get());
  935. ptr = pptr + 1;
  936. }
  937. pptr++;
  938. }
  939. if (pptr > ptr)
  940. {
  941. StringAttr tmp;
  942. tmp.set(ptr, pptr-ptr);
  943. strarray.append(tmp.get());
  944. }
  945. }
  946. int CWsDfuEx::superfileAction(IEspContext &context, const char* action, const char* superfile, StringArray& subfiles,
  947. const char* beforeSubFile, bool existingSuperfile, bool autocreatesuper, bool deleteFile, bool removeSuperfile)
  948. {
  949. if (!action || !*action)
  950. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Superfile action not specified");
  951. if(!strieq(action, "add") && !strieq(action, "remove"))
  952. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Only Add or Remove is allowed.");
  953. if (!superfile || !*superfile)
  954. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Superfile name not specified");
  955. StringBuffer username;
  956. context.getUserID(username);
  957. Owned<IUserDescriptor> userdesc;
  958. if(username.length() > 0)
  959. {
  960. userdesc.setown(createUserDescriptor());
  961. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  962. }
  963. if (!autocreatesuper)
  964. {//a file lock created by the lookup() will be released after '}'
  965. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(superfile, userdesc.get(), true);
  966. if (existingSuperfile)
  967. {
  968. if (!df)
  969. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",superfile);
  970. if(!df->querySuperFile())
  971. throw MakeStringException(ECLWATCH_NOT_SUPERFILE,"%s is not a superfile.",superfile);
  972. }
  973. else if (df)
  974. throw MakeStringException(ECLWATCH_FILE_ALREADY_EXISTS,"The file %s already exists.",superfile);
  975. }
  976. PointerArrayOf<char> subfileArray;
  977. unsigned num = subfiles.length();
  978. if (num > 0)
  979. {
  980. StringBuffer msgHead;
  981. if(username.length() > 0)
  982. msgHead.appendf("%s: Superfile:%s, Subfile(s): ", action, superfile);
  983. else
  984. msgHead.appendf("%s: Superfile:%s, Subfile(s): ", action, superfile);
  985. unsigned filesInMsgBuf = 0;
  986. StringBuffer msgBuf = msgHead;
  987. for(unsigned i = 0; i < num; i++)
  988. {
  989. subfileArray.append((char*) subfiles.item(i));
  990. msgBuf.appendf("%s, ", subfiles.item(i));
  991. filesInMsgBuf++;
  992. if (filesInMsgBuf > 9)
  993. {
  994. PROGLOG("%s",msgBuf.str());
  995. msgBuf = msgHead;
  996. filesInMsgBuf = 0;
  997. }
  998. }
  999. if (filesInMsgBuf > 0)
  1000. PROGLOG("%s", msgBuf.str());
  1001. }
  1002. else
  1003. PROGLOG("%s: %s", action, superfile);
  1004. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  1005. synchronized block(m_superfilemutex);
  1006. if(strieq(action, "add"))
  1007. dfuhelper->addSuper(superfile, userdesc.get(), num, (const char**) subfileArray.getArray(), beforeSubFile, true);
  1008. else
  1009. dfuhelper->removeSuper(superfile, userdesc.get(), num, (const char**) subfileArray.getArray(), deleteFile, removeSuperfile);
  1010. PROGLOG("%s done", action);
  1011. return num;
  1012. }
  1013. bool CWsDfuEx::onAddtoSuperfile(IEspContext &context, IEspAddtoSuperfileRequest &req, IEspAddtoSuperfileResponse &resp)
  1014. {
  1015. try
  1016. {
  1017. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Write, false))
  1018. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to AddtoSuperfile. Permission denied.");
  1019. double version = context.getClientVersion();
  1020. if (version > 1.17)
  1021. {
  1022. const char* backTo = req.getBackToPage();
  1023. if (backTo && *backTo)
  1024. resp.setBackToPage(backTo);
  1025. }
  1026. resp.setSubfiles(req.getSubfiles());
  1027. const char* superfile = req.getSuperfile();
  1028. if (!superfile || !*superfile)
  1029. {
  1030. if (version > 1.15)
  1031. {//Display the subfiles inside a table
  1032. const char* files = req.getSubfiles();
  1033. if (files && *files)
  1034. {
  1035. StringArray subfileNames;
  1036. parseStringArray(files, subfileNames);
  1037. if (subfileNames.length() > 0)
  1038. resp.setSubfileNames(subfileNames);
  1039. }
  1040. }
  1041. return true;//Display a form for user to specify superfile
  1042. }
  1043. if (version > 1.15)
  1044. {
  1045. superfileAction(context, "add", superfile, req.getNames(), NULL, req.getExistingFile(), false, false);
  1046. }
  1047. else
  1048. {
  1049. StringArray subfileNames;
  1050. const char *subfilesStr = req.getSubfiles();
  1051. if (subfilesStr && *subfilesStr)
  1052. parseStringArray(subfilesStr, subfileNames);
  1053. superfileAction(context, "add", superfile, subfileNames, NULL, req.getExistingFile(), false, false);
  1054. }
  1055. resp.setRedirectUrl(StringBuffer("/WsDFU/DFUInfo?Name=").append(superfile));
  1056. }
  1057. catch(IException* e)
  1058. {
  1059. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1060. }
  1061. return true;
  1062. }
  1063. void setDeleteFileResults(const char* fileName, const char* nodeGroup, bool failed, const char *start, const char* text, StringBuffer& resultString,
  1064. IArrayOf<IEspDFUActionInfo>& actionResults)
  1065. {
  1066. if (!fileName || !*fileName)
  1067. return;
  1068. Owned<IEspDFUActionInfo> resultObj = createDFUActionInfo("", "");
  1069. resultObj->setFileName(fileName);
  1070. resultObj->setFailed(failed);
  1071. if (nodeGroup && *nodeGroup)
  1072. resultObj->setNodeGroup(nodeGroup);
  1073. StringBuffer message;
  1074. if (start)
  1075. message.append(start).append(' ');
  1076. message.append(fileName);
  1077. if (nodeGroup && *nodeGroup)
  1078. message.append(" on ").append(nodeGroup);
  1079. if (text && *text)
  1080. message.append(failed ? ": " : " ").append(text);
  1081. resultObj->setActionResult(message);
  1082. resultString.appendf("<Message><Value>%s</Value></Message>", message.str());
  1083. actionResults.append(*resultObj.getClear());
  1084. }
  1085. typedef enum {
  1086. DeleteActionSuccess,
  1087. DeleteActionFailure,
  1088. DeleteActionSkip
  1089. } DeleteActionResult;
  1090. DeleteActionResult doDeleteFile(const char *fn, IUserDescriptor *userdesc, StringArray &superFiles, StringArray &failedFiles,
  1091. const char *auditStr, StringBuffer& returnStr, IArrayOf<IEspDFUActionInfo>& actionResults, bool superFilesOnly, bool removeFromSuperfiles, bool deleteRecursively);
  1092. bool doRemoveFileFromSuperfiles(const char *lfn, IUserDescriptor *userdesc, StringArray &superFiles, StringArray &failedFiles, bool deleteRecursively,
  1093. const char *auditStr, StringBuffer& returnStr, IArrayOf<IEspDFUActionInfo>& actionResults)
  1094. {
  1095. StringArray emptySuperFiles;
  1096. IDistributedFileDirectory &fdir = queryDistributedFileDirectory();
  1097. {
  1098. Owned<IDistributedFile> df = fdir.lookup(lfn, userdesc, true);
  1099. if(!df)
  1100. return false;
  1101. Owned<IDistributedSuperFileIterator> supers = df->getOwningSuperFiles();
  1102. ForEach(*supers)
  1103. {
  1104. IDistributedSuperFile &super = supers->query();
  1105. try
  1106. {
  1107. super.removeSubFile(lfn, false, false, NULL);
  1108. VStringBuffer text("from superfile %s", super.queryLogicalName());
  1109. setDeleteFileResults(lfn, NULL, false, "Removed subfile", text, returnStr, actionResults);
  1110. }
  1111. catch(IException* e)
  1112. {
  1113. StringBuffer emsg;
  1114. VStringBuffer text("from superfile %s: %s", super.queryLogicalName(), e->errorMessage(emsg).str());
  1115. setDeleteFileResults(lfn, NULL, true, "Could not remove subfile ", text, returnStr, actionResults);
  1116. e->Release();
  1117. return false;
  1118. }
  1119. catch(...)
  1120. {
  1121. VStringBuffer text("from superfile %s", super.queryLogicalName());
  1122. setDeleteFileResults(lfn, NULL, true, "Could not remove subfile ", text, returnStr, actionResults);
  1123. return false;
  1124. }
  1125. if (deleteRecursively && super.numSubFiles(false)==0)
  1126. emptySuperFiles.appendUniq(super.queryLogicalName());
  1127. }
  1128. }
  1129. ForEachItemIn(i, emptySuperFiles)
  1130. doDeleteFile(emptySuperFiles.item(i), userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, false, true, deleteRecursively);
  1131. return true;
  1132. }
  1133. DeleteActionResult doDeleteFile(const char *fn, IUserDescriptor *userdesc, StringArray &superFiles, StringArray &failedFiles,
  1134. const char *auditStr, StringBuffer& returnStr, IArrayOf<IEspDFUActionInfo>& actionResults,
  1135. bool superFilesOnly, bool removeFromSuperfiles, bool deleteRecursively)
  1136. {
  1137. StringArray parsed;
  1138. parsed.appendListUniq(fn, "@");
  1139. const char *lfn = parsed.item(0);
  1140. const char *group = NULL;
  1141. if (parsed.length() > 1)
  1142. {
  1143. group = parsed.item(1);
  1144. if (group && (!*group || strieq(group, "null"))) //null is used by new ECLWatch for a superfile
  1145. group = NULL;
  1146. }
  1147. bool isSuper = false;
  1148. if (superFiles.contains(fn) || failedFiles.contains(fn))
  1149. return DeleteActionSkip;
  1150. try
  1151. {
  1152. IDistributedFileDirectory &fdir = queryDistributedFileDirectory();
  1153. {
  1154. Owned<IDistributedFile> df = fdir.lookup(lfn, userdesc, true);
  1155. if(!df)
  1156. {
  1157. PROGLOG("CWsDfuEx::DFUDeleteFiles: %s not found", lfn);
  1158. setDeleteFileResults(lfn, group, true, "File not found", NULL, returnStr, actionResults);
  1159. return DeleteActionFailure;
  1160. }
  1161. isSuper = df->querySuperFile()!=NULL;
  1162. if (superFilesOnly) // skip non-super files on 1st pass
  1163. {
  1164. if(!isSuper)
  1165. return DeleteActionSkip;
  1166. superFiles.append(fn);
  1167. }
  1168. }
  1169. fdir.removeEntry(fn, userdesc, NULL, REMOVE_FILE_SDS_CONNECT_TIMEOUT, true);
  1170. LOG(daliAuditLogCat, "%s,%s", auditStr, fn);
  1171. setDeleteFileResults(lfn, group, false, isSuper ? "Deleted Superfile" : "Deleted File", NULL, returnStr, actionResults);
  1172. }
  1173. catch(IException* e)
  1174. {
  1175. StringBuffer emsg;
  1176. e->errorMessage(emsg);
  1177. if (removeFromSuperfiles && strstr(emsg, "owned by"))
  1178. {
  1179. if (!doRemoveFileFromSuperfiles(lfn, userdesc, superFiles, failedFiles, deleteRecursively, auditStr, returnStr, actionResults))
  1180. return DeleteActionFailure;
  1181. return doDeleteFile(fn, userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, superFilesOnly, false, false);
  1182. }
  1183. if (e->errorCode() == DFSERR_CreateAccessDenied)
  1184. emsg.replaceString("Create ", "Delete ");
  1185. setDeleteFileResults(lfn, group, true, "Could not delete", emsg.str(), returnStr, actionResults);
  1186. e->Release();
  1187. return DeleteActionFailure;
  1188. }
  1189. catch(...)
  1190. {
  1191. setDeleteFileResults(lfn, group, true, "Could not delete", "unknown exception", returnStr, actionResults);
  1192. return DeleteActionFailure;
  1193. }
  1194. return DeleteActionSuccess;
  1195. }
  1196. void doDeleteFiles(StringArray &files, IUserDescriptor *userdesc, StringArray &superFiles, StringArray &failedFiles,
  1197. const char *auditStr, StringBuffer &returnStr, IArrayOf<IEspDFUActionInfo> &actionResults,
  1198. bool superFilesOnly, bool removeFromSuperfiles, bool deleteRecursively)
  1199. {
  1200. ForEachItemIn(i, files)
  1201. {
  1202. const char* fn = files.item(i);
  1203. if(!fn || !*fn)
  1204. continue;
  1205. PROGLOG("Deleting %s", fn);
  1206. if (DeleteActionFailure==doDeleteFile(fn, userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, superFilesOnly, removeFromSuperfiles, deleteRecursively))
  1207. {
  1208. failedFiles.appendUniq(fn);
  1209. PROGLOG("Delete %s failed", fn);
  1210. }
  1211. else
  1212. PROGLOG("Delete %s done", fn);
  1213. }
  1214. }
  1215. inline void doDeleteSuperFiles(StringArray &files, IUserDescriptor *userdesc, StringArray &superFiles,
  1216. StringArray &failedFiles, const char *auditStr, StringBuffer &returnStr, IArrayOf<IEspDFUActionInfo> &actionResults,
  1217. bool removeFromSuperfiles, bool deleteRecursively)
  1218. {
  1219. doDeleteFiles(files, userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, true, removeFromSuperfiles, deleteRecursively);
  1220. }
  1221. inline void doDeleteSubFiles(StringArray &files, IUserDescriptor *userdesc, StringArray &superFiles,
  1222. StringArray &failedFiles, const char *auditStr, StringBuffer &returnStr, IArrayOf<IEspDFUActionInfo> &actionResults,
  1223. bool removeFromSuperfiles, bool deleteRecursively)
  1224. {
  1225. doDeleteFiles(files, userdesc, superFiles, failedFiles, auditStr, returnStr, actionResults, false, removeFromSuperfiles, deleteRecursively);
  1226. }
  1227. bool CWsDfuEx::DFUDeleteFiles(IEspContext &context, IEspDFUArrayActionRequest &req, IEspDFUArrayActionResponse &resp)
  1228. {
  1229. if (isDetachedFromDali())
  1230. throw MakeStringException(ECLWATCH_INVALID_INPUT, "ESP server is detached from Dali. Please try later.");
  1231. double version = context.getClientVersion();
  1232. Owned<IUserDescriptor> userdesc;
  1233. const char *username = context.queryUserId();
  1234. if(username && *username)
  1235. {
  1236. userdesc.setown(createUserDescriptor());
  1237. userdesc->set(username, context.queryPassword(), context.querySignature());
  1238. }
  1239. StringBuffer returnStr, auditStr = (",FileAccess,WsDfu,DELETED,");
  1240. IArrayOf<IEspDFUActionInfo> actionResults;
  1241. StringArray superFiles, failedFiles;
  1242. auditStr.append(espProcess.get());
  1243. auditStr.append(',');
  1244. if (!isEmptyString(username))
  1245. auditStr.append(username).append('@');
  1246. context.getPeer(auditStr);
  1247. doDeleteSuperFiles(req.getLogicalFiles(), userdesc, superFiles, failedFiles, auditStr.str(),
  1248. returnStr, actionResults, req.getRemoveFromSuperfiles(), req.getRemoveRecursively());
  1249. doDeleteSubFiles(req.getLogicalFiles(), userdesc, superFiles, failedFiles, auditStr.str(),
  1250. returnStr, actionResults, req.getRemoveFromSuperfiles(), req.getRemoveRecursively());
  1251. if (version >= 1.27)
  1252. resp.setActionResults(actionResults);
  1253. if (version < 1.33)
  1254. resp.setDFUArrayActionResult(returnStr.str());
  1255. return true;
  1256. }
  1257. bool CWsDfuEx::onDFUArrayAction(IEspContext &context, IEspDFUArrayActionRequest &req, IEspDFUArrayActionResponse &resp)
  1258. {
  1259. try
  1260. {
  1261. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Write, false))
  1262. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to update Logical Files. Permission denied.");
  1263. CDFUArrayActions action = req.getType();
  1264. if (action == DFUArrayActions_Undefined)
  1265. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Action not defined.");
  1266. double version = context.getClientVersion();
  1267. if (version > 1.03)
  1268. {
  1269. StringBuffer backToPage = req.getBackToPage();
  1270. if (backToPage.length() > 0)
  1271. {
  1272. const char* oldStr = "&";
  1273. const char* newStr = "&amp;";
  1274. backToPage.replaceString(oldStr, newStr);
  1275. resp.setBackToPage(backToPage.str());
  1276. }
  1277. }
  1278. if (action == CDFUArrayActions_Delete)
  1279. return DFUDeleteFiles(context, req, resp);
  1280. //the code below is only for legacy ECLWatch. Other application should use AddtoSuperfile.
  1281. StringBuffer username;
  1282. context.getUserID(username);
  1283. Owned<IUserDescriptor> userdesc;
  1284. if(username.length() > 0)
  1285. {
  1286. userdesc.setown(createUserDescriptor());
  1287. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  1288. }
  1289. IArrayOf<IEspDFUActionInfo> actionResults;
  1290. StringBuffer errorStr, subfiles;
  1291. for(unsigned i = 0; i < req.getLogicalFiles().length();i++)
  1292. {
  1293. const char* file = req.getLogicalFiles().item(i);
  1294. if(!file || !*file)
  1295. continue;
  1296. unsigned len = strlen(file);
  1297. char* curfile = new char[len+1];
  1298. const char* cluster = NULL;
  1299. const char *pCh = strchr(file, '@');
  1300. if (pCh)
  1301. {
  1302. len = pCh - file;
  1303. if (len+1 < strlen(file))
  1304. cluster = pCh + 1;
  1305. }
  1306. strncpy(curfile, file, len);
  1307. curfile[len] = 0;
  1308. try
  1309. {
  1310. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(curfile, userdesc.get(), true);
  1311. if (df)
  1312. {
  1313. if (subfiles.length() > 0)
  1314. subfiles.append(",");
  1315. subfiles.append(curfile);
  1316. }
  1317. else
  1318. setDeleteFileResults(file, NULL, true, NULL, "not found", errorStr, actionResults);
  1319. }
  1320. catch(IException* e)
  1321. {
  1322. StringBuffer emsg;
  1323. e->errorMessage(emsg);
  1324. if (e->errorCode() == DFSERR_CreateAccessDenied)
  1325. emsg.replaceString("Create ", "AddtoSuperfile ");
  1326. setDeleteFileResults(file, NULL, true, NULL, emsg.str(), errorStr, actionResults);
  1327. e->Release();
  1328. }
  1329. catch(...)
  1330. {
  1331. setDeleteFileResults(file, NULL, true, NULL, "unknown exception", errorStr, actionResults);
  1332. }
  1333. delete [] curfile;
  1334. }
  1335. if (version >= 1.27)
  1336. resp.setActionResults(actionResults);
  1337. if (errorStr.length())
  1338. {
  1339. if (version < 1.33)
  1340. resp.setDFUArrayActionResult(errorStr.str());
  1341. return false;
  1342. }
  1343. if (version < 1.18)
  1344. resp.setRedirectUrl(StringBuffer("/WsDFU/AddtoSuperfile?Subfiles=").append(subfiles.str()));
  1345. else
  1346. resp.setRedirectTo(subfiles.str());
  1347. }
  1348. catch(IException* e)
  1349. {
  1350. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1351. }
  1352. return true;
  1353. }
  1354. bool CWsDfuEx::onDFUDefFile(IEspContext &context,IEspDFUDefFileRequest &req, IEspDFUDefFileResponse &resp)
  1355. {
  1356. try
  1357. {
  1358. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  1359. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to access DFUDefFile. Permission denied.");
  1360. CDFUDefFileFormat format = req.getFormat();
  1361. if (format == DFUDefFileFormat_Undefined)
  1362. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Invalid format");
  1363. const char* fileName = req.getName();
  1364. if (!fileName || !*fileName)
  1365. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "File name required");
  1366. PROGLOG("DFUDefFile: %s", fileName);
  1367. StringBuffer username;
  1368. context.getUserID(username);
  1369. StringBuffer rawStr,returnStr;
  1370. Owned<IUserDescriptor> userdesc;
  1371. if(username.length() > 0)
  1372. {
  1373. userdesc.setown(createUserDescriptor());
  1374. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  1375. }
  1376. getDefFile(userdesc.get(), req.getName(),rawStr);
  1377. StringBuffer xsltFile;
  1378. xsltFile.append(getCFD()).append("smc_xslt/").append(req.getFormatAsString()).append("_def_file.xslt");
  1379. xsltTransformer(xsltFile.str(),rawStr,returnStr);
  1380. //set the file
  1381. MemoryBuffer buff;
  1382. buff.setBuffer(returnStr.length(), (void*)returnStr.str());
  1383. resp.setDefFile(buff);
  1384. //set the type
  1385. StringBuffer type = "text/";
  1386. if (format == CDFUDefFileFormat_xml)
  1387. type.append("xml");
  1388. else
  1389. type.append("plain");
  1390. resp.setDefFile_mimetype(type.str());
  1391. }
  1392. catch(IException* e)
  1393. {
  1394. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1395. }
  1396. return true;
  1397. }
  1398. IHqlExpression * getEclRecordDefinition(const char * ecl)
  1399. {
  1400. MultiErrorReceiver errs;
  1401. OwnedHqlExpr record = parseQuery(ecl, &errs);
  1402. if (errs.errCount())
  1403. {
  1404. StringBuffer errtext;
  1405. IError *first = errs.firstError();
  1406. first->toString(errtext);
  1407. throw MakeStringException(ECLWATCH_CANNOT_PARSE_ECL_QUERY, "Failed in parsing ECL record definition: %s @ %d:%d.", errtext.str(), first->getColumn(), first->getLine());
  1408. }
  1409. if(!record)
  1410. throw MakeStringException(ECLWATCH_CANNOT_PARSE_ECL_QUERY, "Failed in parsing ECL record definition.");
  1411. return record.getClear();
  1412. }
  1413. IHqlExpression * getEclRecordDefinition(IUserDescriptor* udesc, const char* FileName)
  1414. {
  1415. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(FileName, udesc);
  1416. if(!df)
  1417. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",FileName);
  1418. if(!df->queryAttributes().hasProp("ECL"))
  1419. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"No record definition for file %s.",FileName);
  1420. return getEclRecordDefinition(df->queryAttributes().queryProp("ECL"));
  1421. }
  1422. bool getRecordFormatFromRtlType(MemoryBuffer &binLayout, StringBuffer &jsonLayout, const IPropertyTree &attr, bool includeBin, bool includeJson)
  1423. {
  1424. if (!attr.hasProp("_rtlType"))
  1425. return false;
  1426. try
  1427. {
  1428. MemoryBuffer mb;
  1429. attr.getPropBin("_rtlType", mb);
  1430. if (includeJson)
  1431. {
  1432. Owned<IRtlFieldTypeDeserializer> deserializer(createRtlFieldTypeDeserializer());
  1433. const RtlTypeInfo *typeInfo = deserializer->deserialize(mb);
  1434. dumpTypeInfo(jsonLayout, typeInfo);
  1435. }
  1436. if (includeBin)
  1437. mb.swapWith(binLayout);
  1438. return true;
  1439. }
  1440. catch (IException *e)
  1441. {
  1442. EXCLOG(e, "Failed to process _rtlType");
  1443. e->Release();
  1444. }
  1445. return false;
  1446. }
  1447. bool getRecordFormatFromECL(MemoryBuffer &binLayout, StringBuffer &jsonLayout, const IPropertyTree &attr, bool includeBin, bool includeJson)
  1448. {
  1449. if (!attr.hasProp("ECL"))
  1450. return false;
  1451. try
  1452. {
  1453. const char * kind = attr.queryProp("@kind");
  1454. bool isIndex = (kind && streq(kind, "key"));
  1455. OwnedHqlExpr record = getEclRecordDefinition(attr.queryProp("ECL"));
  1456. MemoryBuffer mb;
  1457. if (attr.hasProp("_record_layout"))
  1458. {
  1459. attr.getPropBin("_record_layout", mb);
  1460. record.setown(patchEclRecordDefinitionFromRecordLayout(record, mb));
  1461. }
  1462. if (includeJson)
  1463. exportJsonType(jsonLayout, record, isIndex);
  1464. if (includeBin)
  1465. exportBinaryType(binLayout, record, isIndex);
  1466. return true;
  1467. }
  1468. catch (IException *e)
  1469. {
  1470. EXCLOG(e, "Failed to process ECL record");
  1471. e->Release();
  1472. }
  1473. return false;
  1474. }
  1475. bool CWsDfuEx::onDFURecordTypeInfo(IEspContext &context, IEspDFURecordTypeInfoRequest &req, IEspDFURecordTypeInfoResponse &resp)
  1476. {
  1477. try
  1478. {
  1479. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  1480. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to access DFURecordTypeInfo. Permission denied.");
  1481. const char* fileName = req.getName();
  1482. if (!fileName || !*fileName)
  1483. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "File name required");
  1484. PROGLOG("DFURecordTypeInfo file: %s", fileName);
  1485. const char* userId = context.queryUserId();
  1486. Owned<IUserDescriptor> userdesc;
  1487. if (userId && *userId)
  1488. {
  1489. userdesc.setown(createUserDescriptor());
  1490. userdesc->set(userId, context.queryPassword(), context.querySignature());
  1491. }
  1492. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(fileName, userdesc);
  1493. if (!df)
  1494. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",fileName);
  1495. MemoryBuffer binLayout;
  1496. StringBuffer jsonLayout;
  1497. if (getRecordFormatFromRtlType(binLayout, jsonLayout, df->queryAttributes(), req.getIncludeBinTypeInfo(), req.getIncludeJsonTypeInfo()) ||
  1498. getRecordFormatFromECL(binLayout.clear(), jsonLayout.clear(), df->queryAttributes(), req.getIncludeBinTypeInfo(), req.getIncludeJsonTypeInfo()))
  1499. {
  1500. if (req.getIncludeBinTypeInfo())
  1501. resp.setBinInfo(binLayout);
  1502. if (req.getIncludeJsonTypeInfo())
  1503. resp.setJsonInfo(jsonLayout);
  1504. }
  1505. }
  1506. catch (IException* e)
  1507. {
  1508. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1509. }
  1510. return true;
  1511. }
  1512. bool CWsDfuEx::onEclRecordTypeInfo(IEspContext &context, IEspEclRecordTypeInfoRequest &req, IEspEclRecordTypeInfoResponse &resp)
  1513. {
  1514. try
  1515. {
  1516. OwnedHqlExpr record = getEclRecordDefinition(req.getEcl());
  1517. if (req.getIncludeJsonTypeInfo())
  1518. {
  1519. StringBuffer jsonFormat;
  1520. exportJsonType(jsonFormat, record, false); // MORE - could allow isIndex to be passed in?
  1521. resp.setJsonInfo(jsonFormat);
  1522. }
  1523. if (req.getIncludeBinTypeInfo())
  1524. {
  1525. MemoryBuffer binFormat;
  1526. exportBinaryType(binFormat, record, false);
  1527. resp.setBinInfo(binFormat);
  1528. }
  1529. }
  1530. catch(IException* e)
  1531. {
  1532. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1533. }
  1534. return true;
  1535. }
  1536. void CWsDfuEx::xsltTransformer(const char* xsltPath,StringBuffer& source,StringBuffer& returnStr)
  1537. {
  1538. if (m_xsl.get() == 0)
  1539. {
  1540. m_xsl.setown(getXslProcessor());
  1541. }
  1542. Owned<IXslTransform> xform = m_xsl->createXslTransform();
  1543. xform->loadXslFromFile(xsltPath);
  1544. xform->setXmlSource(source.str(), source.length()+1);
  1545. xform->transform(returnStr.clear());
  1546. }
  1547. void CWsDfuEx::getDefFile(IUserDescriptor* udesc, const char* FileName,StringBuffer& returnStr)
  1548. {
  1549. OwnedHqlExpr record = getEclRecordDefinition(udesc, FileName);
  1550. Owned<IPropertyTree> data = createPTree("Table", ipt_caseInsensitive);
  1551. exportData(data, record);
  1552. const char* fname=strrchr(FileName,':');
  1553. data->setProp("filename",fname ? fname+1 : FileName);
  1554. toXML(data, returnStr, 0, 0);
  1555. }
  1556. bool CWsDfuEx::checkFileContent(IEspContext &context, IUserDescriptor* udesc, const char * logicalName, const char * cluster)
  1557. {
  1558. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(logicalName, udesc);
  1559. if (!df)
  1560. return false;
  1561. if (!cluster || !stricmp(cluster, ""))
  1562. {
  1563. StringAttr eclCluster;
  1564. const char* wuid = df->queryAttributes().queryProp("@workunit");
  1565. if (wuid && *wuid)
  1566. {
  1567. try
  1568. {
  1569. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  1570. if (factory)
  1571. {
  1572. IConstWorkUnit* wu = factory->openWorkUnit(wuid, context.querySecManager(), context.queryUser());
  1573. if (wu)
  1574. eclCluster.set(wu->queryClusterName());
  1575. }
  1576. }
  1577. catch(...)
  1578. {
  1579. return false;
  1580. }
  1581. }
  1582. if (!eclCluster.length())
  1583. return false;
  1584. }
  1585. bool blocked;
  1586. if (df->isCompressed(&blocked) && !blocked)
  1587. return false;
  1588. IPropertyTree & properties = df->queryAttributes();
  1589. const char * format = properties.queryProp("@format");
  1590. if (format && (stricmp(format,"csv")==0 || memicmp(format, "utf", 3) == 0))
  1591. {
  1592. return true;
  1593. }
  1594. const char * recordEcl = properties.queryProp("ECL");
  1595. if (!recordEcl)
  1596. return false;
  1597. MultiErrorReceiver errs;
  1598. Owned< IHqlExpression> ret = ::parseQuery(recordEcl, &errs);
  1599. return errs.errCount() == 0;
  1600. }
  1601. bool FindInStringArray(StringArray& clusters, const char *cluster)
  1602. {
  1603. bool bFound = false;
  1604. if(cluster && *cluster)
  1605. {
  1606. if (clusters.ordinality())
  1607. {
  1608. ForEachItemIn(i, clusters)
  1609. {
  1610. const char* cluster0 = clusters.item(i);
  1611. if(cluster0 && *cluster0 && !stricmp(cluster, cluster0))
  1612. return true;
  1613. }
  1614. }
  1615. }
  1616. else
  1617. {
  1618. #if 0 //Comment out since clusters are not set for some old files
  1619. if (!clusters.ordinality())
  1620. return true;
  1621. ForEachItemIn(i, clusters)
  1622. {
  1623. const char* cluster0 = clusters.item(i);
  1624. if(cluster0 && !*cluster0)
  1625. {
  1626. return true;
  1627. }
  1628. }
  1629. #else
  1630. return true;
  1631. #endif
  1632. }
  1633. return bFound;
  1634. }
  1635. static void getFilePermission(CDfsLogicalFileName &dlfn, ISecUser & user, IUserDescriptor* udesc, ISecManager* secmgr, SecAccessFlags& permission)
  1636. {
  1637. if (dlfn.isMulti())
  1638. {
  1639. if (!dlfn.isExpanded())
  1640. dlfn.expand(udesc);
  1641. unsigned i = dlfn.multiOrdinality();
  1642. while (i--)
  1643. {
  1644. getFilePermission((CDfsLogicalFileName &)dlfn.multiItem(i), user, udesc, secmgr, permission);
  1645. }
  1646. }
  1647. else
  1648. {
  1649. SecAccessFlags permissionTemp;
  1650. if (dlfn.isForeign())
  1651. {
  1652. permissionTemp = queryDistributedFileDirectory().getFilePermissions(dlfn.get(), udesc);
  1653. }
  1654. else
  1655. {
  1656. StringBuffer scopes;
  1657. dlfn.getScopes(scopes);
  1658. permissionTemp = secmgr->authorizeFileScope(user, scopes.str());
  1659. }
  1660. //Descrease the permission whenever a component has a lower permission.
  1661. if (permissionTemp < permission)
  1662. permission = permissionTemp;
  1663. }
  1664. return;
  1665. }
  1666. bool CWsDfuEx::getUserFilePermission(IEspContext &context, IUserDescriptor* udesc, const char* logicalName, SecAccessFlags& permission)
  1667. {
  1668. ISecManager* secmgr = context.querySecManager();
  1669. if (!secmgr)
  1670. {
  1671. return false;
  1672. }
  1673. StringBuffer username;
  1674. StringBuffer password;
  1675. udesc->getUserName(username);
  1676. if (username.length() < 1)
  1677. {
  1678. DBGLOG("User Name not defined\n");
  1679. return false;
  1680. }
  1681. udesc->getPassword(password);
  1682. Owned<ISecUser> user = secmgr->createUser(username);
  1683. if (!user)
  1684. {
  1685. DBGLOG("User %s not found\n", username.str());
  1686. return false;
  1687. }
  1688. if (password.length() > 0)
  1689. user->credentials().setPassword(password);
  1690. CDfsLogicalFileName dlfn;
  1691. dlfn.set(logicalName);
  1692. //Start from the SecAccess_Full. Decrease the permission whenever a component has a lower permission.
  1693. permission = SecAccess_Full;
  1694. getFilePermission(dlfn, *user, udesc, secmgr, permission);
  1695. return true;
  1696. }
  1697. void CWsDfuEx::getFilePartsOnClusters(IEspContext &context, const char* clusterReq, StringArray& clusters, IDistributedFile* df, IEspDFUFileDetail& FileDetails,
  1698. offset_t& mn, offset_t& mx, offset_t& sum, offset_t& count)
  1699. {
  1700. double version = context.getClientVersion();
  1701. IArrayOf<IConstDFUFilePartsOnCluster>& partsOnClusters = FileDetails.getDFUFilePartsOnClusters();
  1702. ForEachItemIn(i, clusters)
  1703. {
  1704. const char* clusterName = clusters.item(i);
  1705. if (!clusterName || !*clusterName || (clusterReq && *clusterReq && !strieq(clusterReq, clusterName)))
  1706. continue;
  1707. Owned<IEspDFUFilePartsOnCluster> partsOnCluster = createDFUFilePartsOnCluster("","");
  1708. partsOnCluster->setCluster(clusterName);
  1709. IArrayOf<IConstDFUPart>& filePartList = partsOnCluster->getDFUFileParts();
  1710. Owned<IFileDescriptor> fdesc = df->getFileDescriptor(clusterName);
  1711. Owned<IPartDescriptorIterator> pi = fdesc->getIterator();
  1712. ForEach(*pi)
  1713. {
  1714. IPartDescriptor& part = pi->query();
  1715. unsigned partIndex = part.queryPartIndex();
  1716. __int64 size = -1;
  1717. StringBuffer partSizeStr;
  1718. IPropertyTree* partPropertyTree = &part.queryProperties();
  1719. if (!partPropertyTree)
  1720. partSizeStr.set("<N/A>");
  1721. else
  1722. {
  1723. size = partPropertyTree->getPropInt64("@size", -1);
  1724. comma c4(size);
  1725. partSizeStr<<c4;
  1726. count++;
  1727. sum+=size;
  1728. if(size>mx) mx=size;
  1729. if(size<mn) mn=size;
  1730. }
  1731. for (unsigned int i=0; i<part.numCopies(); i++)
  1732. {
  1733. StringBuffer b;
  1734. part.queryNode(i)->endpoint().getUrlStr(b);
  1735. Owned<IEspDFUPart> FilePart = createDFUPart("","");
  1736. FilePart->setId(partIndex+1);
  1737. FilePart->setPartsize(partSizeStr.str());
  1738. if (version >= 1.38)
  1739. FilePart->setPartSizeInt64(size);
  1740. FilePart->setIp(b.str());
  1741. FilePart->setCopy(i+1);
  1742. filePartList.append(*FilePart.getClear());
  1743. }
  1744. }
  1745. if (version >= 1.31)
  1746. {
  1747. IClusterInfo* clusterInfo = fdesc->queryCluster(clusterName);
  1748. if (clusterInfo) //Should be valid. But, check it just in case.
  1749. {
  1750. partsOnCluster->setReplicate(clusterInfo->queryPartDiskMapping().isReplicated());
  1751. Owned<CThorNodeGroup> nodeGroup = thorNodeGroupCache->lookup(clusterName, nodeGroupCacheTimeout);
  1752. if (nodeGroup)
  1753. partsOnCluster->setCanReplicate(nodeGroup->queryCanReplicate());
  1754. const char* defaultDir = fdesc->queryDefaultDir();
  1755. if (defaultDir && *defaultDir)
  1756. {
  1757. DFD_OS os = SepCharBaseOs(getPathSepChar(defaultDir));
  1758. StringBuffer baseDir, repDir;
  1759. clusterInfo->getBaseDir(baseDir, os);
  1760. clusterInfo->getReplicateDir(repDir, os);
  1761. partsOnCluster->setBaseDir(baseDir.str());
  1762. partsOnCluster->setReplicateDir(baseDir.str());
  1763. }
  1764. }
  1765. }
  1766. partsOnClusters.append(*partsOnCluster.getClear());
  1767. }
  1768. }
  1769. void CWsDfuEx::doGetFileDetails(IEspContext &context, IUserDescriptor *udesc, const char *name, const char *cluster,
  1770. const char *querySet, const char *query, const char *description, bool includeJsonTypeInfo, bool includeBinTypeInfo,
  1771. CDFUChangeProtection protect, IEspDFUFileDetail &FileDetails)
  1772. {
  1773. if (!name || !*name)
  1774. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "File name required");
  1775. PROGLOG("doGetFileDetails: %s", name);
  1776. double version = context.getClientVersion();
  1777. if ((version >= 1.38) && !isEmptyString(querySet) && !isEmptyString(query))
  1778. {
  1779. if (getQueryFile(name, querySet, query, FileDetails))
  1780. return;
  1781. }
  1782. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(name, udesc, false, false, true); // lock super-owners
  1783. if(!df)
  1784. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s.",name);
  1785. StringArray clusters;
  1786. df->getClusterNames(clusters);
  1787. if (cluster && *cluster && !FindInStringArray(clusters, cluster))
  1788. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Cannot find file %s on %s.", name, cluster);
  1789. if (protect != CDFUChangeProtection_NoChange)
  1790. {
  1791. StringBuffer protectBy;
  1792. context.getUserID(protectBy);
  1793. if (protectBy.isEmpty())
  1794. protectBy.set("hpcc");
  1795. df->setProtect(protectBy.str(), protect == CDFUChangeProtection_Protect ? true : false);
  1796. }
  1797. offset_t size=queryDistributedFileSystem().getSize(df), recordSize=df->queryAttributes().getPropInt64("@recordSize",0);
  1798. CDateTime dt;
  1799. df->getModificationTime(dt);
  1800. const char* lname=df->queryLogicalName(), *fname=strrchr(lname,':');
  1801. FileDetails.setName(lname);
  1802. FileDetails.setFilename(fname ? fname+1 : lname);
  1803. FileDetails.setDir(df->queryDefaultDir());
  1804. FileDetails.setPathMask(df->queryPartMask());
  1805. if (version >= 1.28)
  1806. {
  1807. StringBuffer buf;
  1808. FileDetails.setPrefix(getPrefixFromLogicalName(lname, buf));
  1809. if (cluster && *cluster)
  1810. FileDetails.setNodeGroup(cluster);
  1811. else if (clusters.length() == 1)
  1812. FileDetails.setNodeGroup(clusters.item(0));
  1813. IArrayOf<IEspDFUFileProtect> protectList;
  1814. Owned<IPropertyTreeIterator> itr= df->queryAttributes().getElements("Protect");
  1815. ForEach(*itr)
  1816. {
  1817. IPropertyTree &tree = itr->query();
  1818. const char *owner = tree.queryProp("@name");
  1819. const char *modified = tree.queryProp("@modified");
  1820. int count = tree.getPropInt("@count", 0);
  1821. Owned<IEspDFUFileProtect> protect= createDFUFileProtect();
  1822. if(owner && *owner)
  1823. protect->setOwner(owner);
  1824. if(modified && *modified)
  1825. protect->setModified(modified);
  1826. protect->setCount(count);
  1827. protectList.append(*protect.getLink());
  1828. }
  1829. FileDetails.setProtectList(protectList);
  1830. }
  1831. StringBuffer strDesc = df->queryAttributes().queryProp("@description");
  1832. if (description)
  1833. {
  1834. DistributedFilePropertyLock lock(df);
  1835. lock.queryAttributes().setProp("@description",description);
  1836. strDesc = description;
  1837. }
  1838. FileDetails.setDescription(strDesc);
  1839. if (version >= 1.38)
  1840. FileDetails.setFileSizeInt64(size);
  1841. comma c1(size);
  1842. StringBuffer tmpstr;
  1843. tmpstr<<c1;
  1844. FileDetails.setFilesize(tmpstr.str());
  1845. bool isKeyFile = isFileKey(df);
  1846. if (isKeyFile || df->isCompressed())
  1847. {
  1848. if (version < 1.22)
  1849. FileDetails.setZipFile(true);
  1850. else
  1851. {
  1852. FileDetails.setIsCompressed(true);
  1853. if (df->queryAttributes().hasProp("@compressedSize"))
  1854. {
  1855. __int64 compressedSize = df->queryAttributes().getPropInt64("@compressedSize");
  1856. FileDetails.setCompressedFileSize(compressedSize);
  1857. if (version >= 1.34)
  1858. {
  1859. Decimal d(((double) compressedSize)/size*100);
  1860. d.round(2);
  1861. FileDetails.setPercentCompressed(d.getCString());
  1862. }
  1863. }
  1864. else if (isKeyFile)
  1865. FileDetails.setCompressedFileSize(size);
  1866. }
  1867. }
  1868. if (version >= 1.38)
  1869. FileDetails.setRecordSizeInt64(recordSize);
  1870. comma c2(recordSize);
  1871. tmpstr.clear();
  1872. tmpstr<<c2;
  1873. FileDetails.setRecordSize(tmpstr.str());
  1874. tmpstr.clear();
  1875. __int64 recordCount = -1;
  1876. if (df->queryAttributes().hasProp("@recordCount"))
  1877. {
  1878. recordCount = df->queryAttributes().getPropInt64("@recordCount");
  1879. }
  1880. else if (recordSize)
  1881. {
  1882. recordCount = size/recordSize;
  1883. }
  1884. if (version >= 1.38)
  1885. FileDetails.setRecordCountInt64(recordCount);
  1886. if (recordCount != -1)
  1887. {
  1888. comma c3(recordCount);
  1889. tmpstr<<c3;
  1890. }
  1891. FileDetails.setRecordCount(tmpstr.str());
  1892. FileDetails.setOwner(df->queryAttributes().queryProp("@owner"));
  1893. FileDetails.setJobName(df->queryAttributes().queryProp("@job"));
  1894. //#14280
  1895. IDistributedSuperFile *sf = df->querySuperFile();
  1896. if(sf)
  1897. {
  1898. StringArray farray;
  1899. Owned<IDistributedFileIterator> iter=sf->getSubFileIterator();
  1900. ForEach(*iter)
  1901. {
  1902. StringBuffer subfileName;
  1903. iter->getName(subfileName);
  1904. farray.append(subfileName.str());
  1905. }
  1906. unsigned numSubFiles = farray.length();
  1907. if(numSubFiles > 0)
  1908. {
  1909. FileDetails.setSubfiles(farray);
  1910. }
  1911. if ((version >= 1.28) && (numSubFiles > 1))
  1912. FileDetails.setBrowseData(false); //ViewKeyFile Cannot handle superfile with multiple subfiles
  1913. FileDetails.setIsSuperfile(true);
  1914. return;
  1915. }
  1916. //#14280
  1917. FileDetails.setWuid(df->queryAttributes().queryProp("@workunit"));
  1918. if (version >= 1.28)
  1919. FileDetails.setNumParts(df->numParts());
  1920. //#17430
  1921. {
  1922. IArrayOf<IEspDFULogicalFile> LogicalFiles;
  1923. Owned<IDistributedSuperFileIterator> iter = df->getOwningSuperFiles();
  1924. if(iter.get() != NULL)
  1925. {
  1926. ForEach(*iter)
  1927. {
  1928. //printf("%s,%s\n",iter->query().queryLogicalName(),lname);
  1929. Owned<IEspDFULogicalFile> File = createDFULogicalFile("","");
  1930. File->setName(iter->queryName());
  1931. LogicalFiles.append(*File.getClear());
  1932. }
  1933. }
  1934. if(LogicalFiles.length() > 0)
  1935. {
  1936. FileDetails.setSuperfiles(LogicalFiles);
  1937. }
  1938. }
  1939. //#17430
  1940. //new (optional) attribute on a logical file (@persistent)
  1941. //indicates the ESP page that shows the details of a file. It indicates
  1942. //whether the file was created with a PERSIST() ecl attribute.
  1943. FileDetails.setPersistent(df->queryAttributes().queryProp("@persistent"));
  1944. //@format - what format the file is (if not fixed with)
  1945. FileDetails.setFormat(df->queryAttributes().queryProp("@format"));
  1946. if ((version >= 1.21) && (df->queryAttributes().hasProp("@kind")))
  1947. FileDetails.setContentType(df->queryAttributes().queryProp("@kind"));
  1948. //@maxRecordSize - what the maximum length of records is
  1949. FileDetails.setMaxRecordSize(df->queryAttributes().queryProp("@maxRecordSize"));
  1950. //@csvSeparate - separators between fields for a CSV/utf file
  1951. FileDetails.setCsvSeparate(df->queryAttributes().queryProp("@csvSeparate"));
  1952. //@csvQuote - character used to quote fields for a csv/utf file.
  1953. FileDetails.setCsvQuote(df->queryAttributes().queryProp("@csvQuote"));
  1954. //@csvTerminate - characters used to terminate a record in a csv.utf file
  1955. FileDetails.setCsvTerminate(df->queryAttributes().queryProp("@csvTerminate"));
  1956. //@csvEscape - character used to define escape for a csv/utf file.
  1957. if (version >= 1.20)
  1958. FileDetails.setCsvEscape(df->queryAttributes().queryProp("@csvEscape"));
  1959. //Time and date of the file
  1960. tmpstr.clear();
  1961. dt.getDateString(tmpstr);
  1962. tmpstr.append(" ");
  1963. dt.getTimeString(tmpstr);
  1964. FileDetails.setModified(tmpstr.str());
  1965. if(df->queryAttributes().hasProp("ECL"))
  1966. FileDetails.setEcl(df->queryAttributes().queryProp("ECL"));
  1967. StringBuffer clusterStr;
  1968. ForEachItemIn(i, clusters)
  1969. {
  1970. if (!clusterStr.length())
  1971. clusterStr.append(clusters.item(i));
  1972. else
  1973. clusterStr.append(",").append(clusters.item(i));
  1974. }
  1975. if (clusterStr.length() > 0)
  1976. {
  1977. if (!checkFileContent(context, udesc, name, clusterStr.str()))
  1978. FileDetails.setShowFileContent(false);
  1979. if (version > 1.05)
  1980. {
  1981. bool fromRoxieCluster = false;
  1982. StringArray roxieClusterNames;
  1983. IArrayOf<IEspTpCluster> roxieclusters;
  1984. CTpWrapper dummy;
  1985. dummy.getClusterProcessList(eqRoxieCluster, roxieclusters);
  1986. ForEachItemIn(k, roxieclusters)
  1987. {
  1988. IEspTpCluster& r_cluster = roxieclusters.item(k);
  1989. StringBuffer sName = r_cluster.getName();
  1990. if (FindInStringArray(clusters, sName.str()))
  1991. {
  1992. fromRoxieCluster = true;
  1993. break;
  1994. }
  1995. }
  1996. FileDetails.setFromRoxieCluster(fromRoxieCluster);
  1997. }
  1998. }
  1999. offset_t mn=LLC(0x7fffffffffffffff), mx=0, sum=0, count=0;
  2000. if (version >= 1.25)
  2001. getFilePartsOnClusters(context, cluster, clusters, df, FileDetails, mn, mx, sum, count);
  2002. else
  2003. {
  2004. FileDetails.setCluster(clusters.item(0));
  2005. IArrayOf<IConstDFUPart>& PartList = FileDetails.getDFUFileParts();
  2006. Owned<IDistributedFilePartIterator> pi = df->getIterator();
  2007. ForEach(*pi)
  2008. {
  2009. Owned<IDistributedFilePart> part = &pi->get();
  2010. for (unsigned int i=0; i<part->numCopies(); i++)
  2011. {
  2012. Owned<IEspDFUPart> FilePart = createDFUPart("","");
  2013. StringBuffer b;
  2014. part->queryNode(i)->endpoint().getUrlStr(b);
  2015. FilePart->setId(part->getPartIndex()+1);
  2016. FilePart->setCopy(i+1);
  2017. FilePart->setIp(b.str());
  2018. FilePart->setPartsize("<N/A>");
  2019. try
  2020. {
  2021. offset_t size=queryDistributedFileSystem().getSize(part);
  2022. if (version >= 1.38)
  2023. FilePart->setPartSizeInt64(size);
  2024. comma c4(size);
  2025. tmpstr.clear();
  2026. tmpstr<<c4;
  2027. FilePart->setPartsize(tmpstr.str());
  2028. if(size!=-1)
  2029. {
  2030. count+=1;
  2031. sum+=size;
  2032. if(size>mx) mx=size;
  2033. if(size<mn) mn=size;
  2034. }
  2035. }
  2036. catch(IException *e)
  2037. {
  2038. StringBuffer msg;
  2039. ERRLOG("Exception %d:%s in WS_DFU queryDistributedFileSystem().getSize()", e->errorCode(), e->errorMessage(msg).str());
  2040. e->Release();
  2041. }
  2042. catch(...)
  2043. {
  2044. ERRLOG("Unknown exception in WS_DFU queryDistributedFileSystem().getSize()");
  2045. }
  2046. PartList.append(*FilePart.getClear());
  2047. }
  2048. }
  2049. }
  2050. if(count)
  2051. {
  2052. IEspDFUFileStat& Stat = FileDetails.updateStat();
  2053. offset_t avg=sum/count;
  2054. offset_t minSkew = avg-mn;
  2055. offset_t maxSkew = mx-avg;
  2056. if (version >= 1.38)
  2057. {
  2058. Stat.setMinSkewInt64(minSkew);
  2059. Stat.setMaxSkewInt64(maxSkew);
  2060. }
  2061. comma c5(minSkew);
  2062. tmpstr.clear();
  2063. tmpstr<<c5;
  2064. Stat.setMinSkew(tmpstr.str());
  2065. comma c6(maxSkew);
  2066. tmpstr.clear();
  2067. tmpstr<<c6;
  2068. Stat.setMaxSkew(tmpstr.str());
  2069. }
  2070. if (version > 1.06)
  2071. {
  2072. const char *wuid = df->queryAttributes().queryProp("@workunit");
  2073. if (wuid && *wuid && (wuid[0]=='W'))
  2074. {
  2075. try
  2076. {
  2077. CWUWrapper wu(wuid, context);
  2078. StringArray graphs;
  2079. Owned<IPropertyTreeIterator> f=&wu->getFileIterator();
  2080. ForEach(*f)
  2081. {
  2082. IPropertyTree &query = f->query();
  2083. const char *fileName = query.queryProp("@name");
  2084. const char *graphName = query.queryProp("@graph");
  2085. if (!fileName || !graphName || !*graphName || stricmp(fileName, name))
  2086. continue;
  2087. graphs.append(graphName);
  2088. }
  2089. FileDetails.setGraphs(graphs);
  2090. }
  2091. catch(...)
  2092. {
  2093. DBGLOG("Failed in retrieving graphs from workunit %s", wuid);
  2094. }
  2095. }
  2096. }
  2097. if (version > 1.08 && udesc)
  2098. {
  2099. SecAccessFlags permission;
  2100. if (getUserFilePermission(context, udesc, name, permission))
  2101. {
  2102. switch (permission)
  2103. {
  2104. case SecAccess_Full:
  2105. FileDetails.setUserPermission("Full Access Permission");
  2106. break;
  2107. case SecAccess_Write:
  2108. FileDetails.setUserPermission("Write Access Permission");
  2109. break;
  2110. case SecAccess_Read:
  2111. FileDetails.setUserPermission("Read Access Permission");
  2112. break;
  2113. case SecAccess_Access:
  2114. FileDetails.setUserPermission("Access Permission");
  2115. break;
  2116. case SecAccess_None:
  2117. FileDetails.setUserPermission("None Access Permission");
  2118. break;
  2119. default:
  2120. FileDetails.setUserPermission("Permission Unknown");
  2121. break;
  2122. }
  2123. }
  2124. }
  2125. if (includeJsonTypeInfo||includeBinTypeInfo)
  2126. {
  2127. MemoryBuffer binLayout;
  2128. StringBuffer jsonLayout;
  2129. if (getRecordFormatFromRtlType(binLayout, jsonLayout, df->queryAttributes(), includeBinTypeInfo, includeJsonTypeInfo) ||
  2130. getRecordFormatFromECL(binLayout.clear(), jsonLayout.clear(), df->queryAttributes(), includeBinTypeInfo, includeJsonTypeInfo))
  2131. {
  2132. if (includeBinTypeInfo)
  2133. FileDetails.setBinInfo(binLayout);
  2134. if (includeJsonTypeInfo)
  2135. FileDetails.setJsonInfo(jsonLayout);
  2136. }
  2137. }
  2138. PROGLOG("doGetFileDetails: %s done", name);
  2139. }
  2140. bool CWsDfuEx::getQueryFile(const char *logicalName, const char *querySet, const char *queryID, IEspDFUFileDetail &fileDetails)
  2141. {
  2142. Owned<IConstWUClusterInfo> info = getTargetClusterInfo(querySet);
  2143. if (!info || (info->getPlatform()!=RoxieCluster))
  2144. return false;
  2145. SCMStringBuffer process;
  2146. info->getRoxieProcess(process);
  2147. if (!process.length())
  2148. return false;
  2149. Owned<IHpccPackageSet> ps = createPackageSet(process.str());
  2150. if (!ps)
  2151. return false;
  2152. const IHpccPackageMap *pm = ps->queryActiveMap(querySet);
  2153. if (!pm)
  2154. return false;
  2155. const IHpccPackage *pkg = pm->matchPackage(queryID);
  2156. if (!pkg)
  2157. return false;
  2158. const char *pkgid = pkg->locateSuperFile(logicalName);
  2159. if (!pkgid)
  2160. return false;
  2161. fileDetails.setName(logicalName);
  2162. fileDetails.setIsSuperfile(true);
  2163. fileDetails.setPackageID(pkgid);
  2164. StringArray subFiles;
  2165. Owned<ISimpleSuperFileEnquiry> ssfe = pkg->resolveSuperFile(logicalName);
  2166. if (ssfe && ssfe->numSubFiles()>0)
  2167. {
  2168. unsigned count = ssfe->numSubFiles();
  2169. while (count--)
  2170. {
  2171. StringBuffer subfile;
  2172. ssfe->getSubFileName(count, subfile);
  2173. subFiles.append(subfile.str());
  2174. }
  2175. if (!subFiles.empty())
  2176. fileDetails.setSubfiles(subFiles);
  2177. }
  2178. return true;
  2179. }
  2180. void CWsDfuEx::getLogicalFileAndDirectory(IEspContext &context, IUserDescriptor* udesc, const char *dirname,
  2181. bool includeSuperOwner, IArrayOf<IEspDFULogicalFile>& logicalFiles, int& numFiles, int& numDirs)
  2182. {
  2183. double version = context.getClientVersion();
  2184. if (dirname && *dirname)
  2185. PROGLOG("getLogicalFileAndDirectory: %s", dirname);
  2186. else
  2187. PROGLOG("getLogicalFileAndDirectory: folder not specified");
  2188. numFiles = 0;
  2189. numDirs = 0;
  2190. if (dirname && *dirname)
  2191. {
  2192. StringBuffer filterBuf;
  2193. setFileNameFilter(NULL, dirname, filterBuf);
  2194. if (includeSuperOwner)
  2195. filterBuf.append(DFUQFTincludeFileAttr).append(DFUQFilterSeparator).append(DFUQSFAOincludeSuperOwner).append(DFUQFilterSeparator);
  2196. //filters used to filter query result received from dali server.
  2197. DFUQResultField localFilters[8];
  2198. localFilters[0] = DFUQRFterm;
  2199. DFUQResultField sortOrder[] = {DFUQRFterm};
  2200. __int64 cacheHint = 0; //No page
  2201. unsigned totalFiles = 0;
  2202. bool allMatchingFilesReceived = true;
  2203. Owned<IDFAttributesIterator> it = queryDistributedFileDirectory().getLogicalFiles(udesc, sortOrder, filterBuf.str(),
  2204. localFilters, NULL, 0, (unsigned)-1, &cacheHint, &totalFiles, &allMatchingFilesReceived, false, false);
  2205. if(!it)
  2206. throw MakeStringException(ECLWATCH_CANNOT_GET_FILE_ITERATOR,"Cannot get LogicalFile information from file system.");
  2207. ForEach(*it)
  2208. addToLogicalFileList(it->query(), NULL, version, logicalFiles);
  2209. numFiles = totalFiles;
  2210. }
  2211. Owned<IDFScopeIterator> iter = queryDistributedFileDirectory().getScopeIterator(udesc,dirname,false);
  2212. if(iter)
  2213. {
  2214. ForEach(*iter)
  2215. {
  2216. const char *scope = iter->query();
  2217. if (scope && *scope)
  2218. {
  2219. Owned<IEspDFULogicalFile> file = createDFULogicalFile("","");
  2220. file->setDirectory(scope);
  2221. file->setIsDirectory(true);
  2222. logicalFiles.append(*file.getClear());
  2223. numDirs++;
  2224. }
  2225. }
  2226. }
  2227. }
  2228. bool CWsDfuEx::onDFUFileView(IEspContext &context, IEspDFUFileViewRequest &req, IEspDFUFileViewResponse &resp)
  2229. {
  2230. try
  2231. {
  2232. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  2233. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to Browse Files by Scope. Permission denied.");
  2234. Owned<IUserDescriptor> userdesc;
  2235. StringBuffer username;
  2236. context.getUserID(username);
  2237. if(username.length() > 0)
  2238. {
  2239. userdesc.setown(createUserDescriptor());
  2240. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  2241. }
  2242. int numDirs = 0;
  2243. int numFiles = 0;
  2244. IArrayOf<IEspDFULogicalFile> logicalFiles;
  2245. getLogicalFileAndDirectory(context, userdesc.get(), req.getScope(), !req.getIncludeSuperOwner_isNull() && req.getIncludeSuperOwner(), logicalFiles, numFiles, numDirs);
  2246. if (numFiles > 0)
  2247. resp.setNumFiles(numFiles);
  2248. if (req.getScope() && *req.getScope())
  2249. resp.setScope(req.getScope());
  2250. else
  2251. resp.setScope("");
  2252. resp.setDFULogicalFiles(logicalFiles);
  2253. }
  2254. catch(IException* e)
  2255. {
  2256. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2257. }
  2258. return true;
  2259. }
  2260. __int64 CWsDfuEx::findPositionBySize(const __int64 size, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2261. {
  2262. __int64 addToPos = -1;
  2263. ForEachItemIn(i, LogicalFiles)
  2264. {
  2265. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2266. const char* sSize = File.getLongSize();
  2267. __int64 nSize = atoi64_l(sSize,strlen(sSize));
  2268. if (descend && size > nSize)
  2269. {
  2270. addToPos = i;
  2271. break;
  2272. }
  2273. if (!descend && size < nSize)
  2274. {
  2275. addToPos = i;
  2276. break;
  2277. }
  2278. }
  2279. return addToPos;
  2280. }
  2281. __int64 CWsDfuEx::findPositionByParts(const __int64 parts, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2282. {
  2283. __int64 addToPos = -1;
  2284. ForEachItemIn(i, LogicalFiles)
  2285. {
  2286. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2287. const char* sParts = File.getParts();
  2288. __int64 nParts = atoi64_l(sParts,strlen(sParts));
  2289. if (descend && parts > nParts)
  2290. {
  2291. addToPos = i;
  2292. break;
  2293. }
  2294. if (!descend && parts < nParts)
  2295. {
  2296. addToPos = i;
  2297. break;
  2298. }
  2299. }
  2300. return addToPos;
  2301. }
  2302. __int64 CWsDfuEx::findPositionByRecords(const __int64 records, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2303. {
  2304. __int64 addToPos = -1;
  2305. ForEachItemIn(i, LogicalFiles)
  2306. {
  2307. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2308. const char* sRecords = File.getLongRecordCount();
  2309. __int64 nRecords = atoi64_l(sRecords,strlen(sRecords));
  2310. if (descend && records > nRecords)
  2311. {
  2312. addToPos = i;
  2313. break;
  2314. }
  2315. if (!descend && records < nRecords)
  2316. {
  2317. addToPos = i;
  2318. break;
  2319. }
  2320. }
  2321. return addToPos;
  2322. }
  2323. __int64 CWsDfuEx::findPositionByName(const char *name, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2324. {
  2325. if (!name || (strlen(name) < 1))
  2326. {
  2327. if (descend)
  2328. return -1;
  2329. else
  2330. return 0;
  2331. }
  2332. __int64 addToPos = -1;
  2333. ForEachItemIn(i, LogicalFiles)
  2334. {
  2335. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2336. const char *Name = File.getName();
  2337. if (!Name)
  2338. continue;
  2339. if (descend && strcmp(name, Name)>0)
  2340. {
  2341. addToPos = i;
  2342. break;
  2343. }
  2344. if (!descend && strcmp(name, Name)<0)
  2345. {
  2346. addToPos = i;
  2347. break;
  2348. }
  2349. }
  2350. return addToPos;
  2351. }
  2352. __int64 CWsDfuEx::findPositionByNodeGroup(double version, const char *node, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2353. {
  2354. if (!node || !*node)
  2355. {
  2356. if (descend)
  2357. return -1;
  2358. else
  2359. return 0;
  2360. }
  2361. __int64 addToPos = -1;
  2362. ForEachItemIn(i, LogicalFiles)
  2363. {
  2364. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2365. const char *nodeGroup = NULL;
  2366. if (version < 1.26)
  2367. nodeGroup = File.getClusterName();
  2368. else
  2369. nodeGroup = File.getNodeGroup();
  2370. if (!nodeGroup)
  2371. continue;
  2372. if (descend && strcmp(node, nodeGroup)>0)
  2373. {
  2374. addToPos = i;
  2375. break;
  2376. }
  2377. if (!descend && strcmp(node, nodeGroup)<0)
  2378. {
  2379. addToPos = i;
  2380. break;
  2381. }
  2382. }
  2383. return addToPos;
  2384. }
  2385. __int64 CWsDfuEx::findPositionByOwner(const char *owner, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2386. {
  2387. if (!owner || (strlen(owner) < 1))
  2388. {
  2389. if (descend)
  2390. return -1;
  2391. else
  2392. return 0;
  2393. }
  2394. __int64 addToPos = -1;
  2395. ForEachItemIn(i, LogicalFiles)
  2396. {
  2397. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2398. const char *Owner = File.getOwner();
  2399. if (!Owner)
  2400. continue;
  2401. if (descend && strcmp(owner, Owner)>0)
  2402. {
  2403. addToPos = i;
  2404. break;
  2405. }
  2406. if (!descend && strcmp(owner, Owner)<0)
  2407. {
  2408. addToPos = i;
  2409. break;
  2410. }
  2411. }
  2412. return addToPos;
  2413. }
  2414. __int64 CWsDfuEx::findPositionByDate(const char *datetime, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2415. {
  2416. if (!datetime || (strlen(datetime) < 1))
  2417. {
  2418. if (descend)
  2419. return -1;
  2420. else
  2421. return 0;
  2422. }
  2423. __int64 addToPos = -1;
  2424. ForEachItemIn(i, LogicalFiles)
  2425. {
  2426. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2427. const char *modDate = File.getModified();
  2428. if (!modDate)
  2429. continue;
  2430. if (descend && strcmp(datetime, modDate)>0)
  2431. {
  2432. addToPos = i;
  2433. break;
  2434. }
  2435. if (!descend && strcmp(datetime, modDate)<0)
  2436. {
  2437. addToPos = i;
  2438. break;
  2439. }
  2440. }
  2441. return addToPos;
  2442. }
  2443. __int64 CWsDfuEx::findPositionByDescription(const char *description, bool descend, IArrayOf<IEspDFULogicalFile>& LogicalFiles)
  2444. {
  2445. if (!description || (strlen(description) < 1))
  2446. {
  2447. if (descend)
  2448. return -1;
  2449. else
  2450. return 0;
  2451. }
  2452. __int64 addToPos = -1;
  2453. ForEachItemIn(i, LogicalFiles)
  2454. {
  2455. IEspDFULogicalFile& File = LogicalFiles.item(i);
  2456. const char *Description = File.getDescription();
  2457. if (!Description)
  2458. continue;
  2459. if (descend && strcmp(description, Description)>0)
  2460. {
  2461. addToPos = i;
  2462. break;
  2463. }
  2464. if (!descend && strcmp(description, Description)<0)
  2465. {
  2466. addToPos = i;
  2467. break;
  2468. }
  2469. }
  2470. return addToPos;
  2471. }
  2472. //The code inside this method is copied from previous code for legacy (< 5.0) dali support
  2473. void CWsDfuEx::getAPageOfSortedLogicalFile(IEspContext &context, IUserDescriptor* udesc, IEspDFUQueryRequest & req, IEspDFUQueryResponse & resp)
  2474. {
  2475. double version = context.getClientVersion();
  2476. IArrayOf<IEspDFULogicalFile> LogicalFiles;
  2477. StringBuffer filter;
  2478. const char* fname = req.getLogicalName();
  2479. if(fname && *fname)
  2480. {
  2481. filter.append(fname);
  2482. }
  2483. else
  2484. {
  2485. if(req.getPrefix() && *req.getPrefix())
  2486. {
  2487. filter.append(req.getPrefix());
  2488. filter.append("::");
  2489. }
  2490. filter.append("*");
  2491. }
  2492. Owned<IDFAttributesIterator> fi;
  2493. bool bNotInSuperfile = false;
  2494. const char* sFileType = req.getFileType();
  2495. if (sFileType && !stricmp(sFileType, "Not in Superfiles"))
  2496. {
  2497. bNotInSuperfile = true;
  2498. }
  2499. if (bNotInSuperfile)
  2500. {
  2501. fi.setown(createSubFileFilter(
  2502. queryDistributedFileDirectory().getDFAttributesIterator(filter.toLowerCase().str(),udesc,true,true, NULL),udesc,false)); // NB wrapper owns wrapped iterator
  2503. }
  2504. else
  2505. {
  2506. fi.setown(queryDistributedFileDirectory().getDFAttributesIterator(filter.toLowerCase().str(), udesc,true,true, NULL));
  2507. }
  2508. if(!fi)
  2509. throw MakeStringException(ECLWATCH_CANNOT_GET_FILE_ITERATOR,"Cannot get information from file system.");
  2510. StringBuffer wuFrom, wuTo;
  2511. if(req.getStartDate() && *req.getStartDate())
  2512. {
  2513. CDateTime wuTime;
  2514. wuTime.setString(req.getStartDate(),NULL,true);
  2515. unsigned year, month, day, hour, minute, second, nano;
  2516. wuTime.getDate(year, month, day, true);
  2517. wuTime.getTime(hour, minute, second, nano, true);
  2518. wuFrom.appendf("%4d-%02d-%02d %02d:%02d:%02d",year,month,day,hour,minute,second);
  2519. }
  2520. if(req.getEndDate() && *req.getEndDate())
  2521. {
  2522. CDateTime wuTime;
  2523. wuTime.setString(req.getEndDate(),NULL,true);
  2524. unsigned year, month, day, hour, minute, second, nano;
  2525. wuTime.getDate(year, month, day, true);
  2526. wuTime.getTime(hour, minute, second, nano, true);
  2527. wuTo.appendf("%4d-%02d-%02d %02d:%02d:%02d",year,month,day,hour,minute,second);
  2528. }
  2529. StringBuffer sortBy;
  2530. if(req.getSortby() && *req.getSortby())
  2531. {
  2532. sortBy.append(req.getSortby());
  2533. }
  2534. unsigned pagesize = req.getPageSize();
  2535. if (pagesize < 1)
  2536. {
  2537. pagesize = 100;
  2538. }
  2539. __int64 displayStartReq = 1;
  2540. if (req.getPageStartFrom() > 0)
  2541. displayStartReq = req.getPageStartFrom();
  2542. __int64 displayStart = displayStartReq - 1;
  2543. __int64 displayEnd = displayStart + pagesize;
  2544. bool descending = req.getDescending();
  2545. const int nFirstN = req.getFirstN();
  2546. const char* sFirstNType = req.getFirstNType();
  2547. const __int64 nFileSizeFrom = req.getFileSizeFrom();
  2548. const __int64 nFileSizeTo = req.getFileSizeTo();
  2549. if (nFirstN > 0)
  2550. {
  2551. displayStart = 0;
  2552. displayEnd = nFirstN;
  2553. if (!stricmp(sFirstNType, "newest"))
  2554. {
  2555. sortBy.set("Modified");
  2556. descending = true;
  2557. }
  2558. else if (!stricmp(sFirstNType, "oldest"))
  2559. {
  2560. sortBy.set("Modified");
  2561. descending = false;
  2562. }
  2563. else if (!stricmp(sFirstNType, "largest"))
  2564. {
  2565. sortBy.set("FileSize");
  2566. descending = true;
  2567. }
  2568. else if (!stricmp(sFirstNType, "smallest"))
  2569. {
  2570. sortBy.set("FileSize");
  2571. descending = false;
  2572. }
  2573. pagesize = nFirstN;
  2574. }
  2575. StringArray roxieClusterNames;
  2576. IArrayOf<IEspTpCluster> roxieclusters;
  2577. CTpWrapper dummy;
  2578. dummy.getClusterProcessList(eqRoxieCluster, roxieclusters);
  2579. ForEachItemIn(k, roxieclusters)
  2580. {
  2581. IEspTpCluster& cluster = roxieclusters.item(k);
  2582. StringBuffer sName = cluster.getName();
  2583. roxieClusterNames.append(sName.str());
  2584. }
  2585. StringArray nodeGroupsReq;
  2586. const char* nodeGroupsReqString = req.getNodeGroup();
  2587. if (nodeGroupsReqString && *nodeGroupsReqString)
  2588. nodeGroupsReq.appendListUniq(nodeGroupsReqString, ",");
  2589. StringBuffer size;
  2590. __int64 totalFiles = 0;
  2591. IArrayOf<IEspDFULogicalFile> LogicalFileList;
  2592. ForEach(*fi)
  2593. {
  2594. IPropertyTree &attr=fi->query();
  2595. const char* logicalName=attr.queryProp("@name");
  2596. if (!logicalName || (logicalName[0] == 0))
  2597. continue;
  2598. try
  2599. {
  2600. StringBuffer pref;
  2601. const char *c=strstr(logicalName, "::");
  2602. if (c)
  2603. pref.append(c-logicalName, logicalName);
  2604. else
  2605. pref.append(logicalName);
  2606. const char* owner=attr.queryProp("@owner");
  2607. if (req.getOwner() && *req.getOwner()!=0)
  2608. {
  2609. if (!owner || stricmp(owner, req.getOwner()))
  2610. continue;
  2611. }
  2612. StringArray nodeGroups;
  2613. StringArray fileNodeGroups;
  2614. if (getFileGroups(&attr,fileNodeGroups)==0)
  2615. {
  2616. if (!nodeGroupsReq.length())
  2617. nodeGroups.append("");
  2618. }
  2619. else if (nodeGroupsReq.length() > 0) // check specified cluster name in list
  2620. {
  2621. ForEachItemIn(ii,nodeGroupsReq)
  2622. {
  2623. const char* nodeGroupReq = nodeGroupsReq.item(ii);
  2624. ForEachItemIn(i,fileNodeGroups)
  2625. {
  2626. if (strieq(fileNodeGroups.item(i), nodeGroupReq))
  2627. {
  2628. nodeGroups.append(nodeGroupReq);
  2629. break;
  2630. }
  2631. }
  2632. }
  2633. }
  2634. else if (fileNodeGroups.length())
  2635. {
  2636. ForEachItemIn(i,fileNodeGroups)
  2637. nodeGroups.append(fileNodeGroups.item(i));
  2638. }
  2639. if (sFileType && *sFileType)
  2640. {
  2641. bool bHasSubFiles = attr.hasProp("@numsubfiles");
  2642. if (bHasSubFiles && (bNotInSuperfile || !stricmp(sFileType, "Logical Files Only")))
  2643. continue;
  2644. else if (!bHasSubFiles && !stricmp(sFileType, "Superfiles Only"))
  2645. continue;
  2646. }
  2647. __int64 recordSize=attr.getPropInt64("@recordSize",0), size=attr.getPropInt64("@size",-1);
  2648. if (nFileSizeFrom > 0 && size < nFileSizeFrom)
  2649. continue;
  2650. if (nFileSizeTo > 0 && size > nFileSizeTo)
  2651. continue;
  2652. StringBuffer modf(attr.queryProp("@modified"));
  2653. char* t=(char *) strchr(modf.str(),'T');
  2654. if(t) *t=' ';
  2655. if (wuFrom.length() && strcmp(modf.str(),wuFrom.str())<0)
  2656. continue;
  2657. if (wuTo.length() && strcmp(modf.str(),wuTo.str())>0)
  2658. continue;
  2659. __int64 parts = 0;
  2660. if(!attr.hasProp("@numsubfiles"))
  2661. parts = attr.getPropInt64("@numparts");
  2662. __int64 records = 0;
  2663. if (attr.hasProp("@recordCount"))
  2664. records = attr.getPropInt64("@recordCount");
  2665. else if(recordSize)
  2666. records = size/recordSize;
  2667. const char* desc = attr.queryProp("@description");
  2668. ForEachItemIn(i, nodeGroups)
  2669. {
  2670. const char* nodeGroup = nodeGroups.item(i);
  2671. __int64 addToPos = -1; //Add to tail
  2672. if (stricmp(sortBy, "FileSize")==0)
  2673. {
  2674. addToPos = findPositionBySize(size, descending, LogicalFileList);
  2675. }
  2676. else if (stricmp(sortBy, "Parts")==0)
  2677. {
  2678. addToPos = findPositionByParts(parts, descending, LogicalFileList);
  2679. }
  2680. else if (stricmp(sortBy, "Owner")==0)
  2681. {
  2682. addToPos = findPositionByOwner(owner, descending, LogicalFileList);
  2683. }
  2684. else if (stricmp(sortBy, "NodeGroup")==0)
  2685. {
  2686. addToPos = findPositionByNodeGroup(version, nodeGroup, descending, LogicalFileList);
  2687. }
  2688. else if (stricmp(sortBy, "Records")==0)
  2689. {
  2690. addToPos = findPositionByRecords(records, descending, LogicalFileList);
  2691. }
  2692. else if (stricmp(sortBy, "Modified")==0)
  2693. {
  2694. addToPos = findPositionByDate(modf.str(), descending, LogicalFileList);
  2695. }
  2696. else if (stricmp(sortBy, "Description")==0)
  2697. {
  2698. addToPos = findPositionByDescription(desc, descending, LogicalFileList);
  2699. }
  2700. else
  2701. {
  2702. addToPos = findPositionByName(logicalName, descending, LogicalFileList);
  2703. }
  2704. totalFiles++;
  2705. if (addToPos < 0 && (totalFiles > displayEnd))
  2706. continue;
  2707. Owned<IEspDFULogicalFile> File = createDFULogicalFile("","");
  2708. File->setPrefix(pref);
  2709. if (version < 1.26)
  2710. File->setClusterName(nodeGroup);
  2711. else
  2712. File->setNodeGroup(nodeGroup);
  2713. File->setName(logicalName);
  2714. File->setOwner(owner);
  2715. File->setDescription(desc);
  2716. File->setModified(modf.str());
  2717. File->setReplicate(true);
  2718. ForEachItemIn(j, roxieClusterNames)
  2719. {
  2720. const char* roxieClusterName = roxieClusterNames.item(j);
  2721. if (roxieClusterName && nodeGroup && strieq(roxieClusterName, nodeGroup))
  2722. {
  2723. File->setFromRoxieCluster(true);
  2724. break;
  2725. }
  2726. }
  2727. bool bSuperfile = false;
  2728. int numSubFiles = attr.hasProp("@numsubfiles");
  2729. if(!numSubFiles)
  2730. {
  2731. File->setDirectory(attr.queryProp("@directory"));
  2732. File->setParts(attr.queryProp("@numparts"));
  2733. }
  2734. else
  2735. {
  2736. bSuperfile = true;
  2737. }
  2738. File->setIsSuperfile(bSuperfile);
  2739. if (version < 1.22)
  2740. File->setIsZipfile(isCompressed(attr));
  2741. else
  2742. {
  2743. File->setIsCompressed(isCompressed(attr));
  2744. if (attr.hasProp("@compressedSize"))
  2745. File->setCompressedFileSize(attr.getPropInt64("@compressedSize"));
  2746. }
  2747. //File->setBrowseData(bKeyFile); //Bug: 39750 - All files should be viewable through ViewKeyFile function
  2748. if (numSubFiles > 1) //Bug 41379 - ViewKeyFile Cannot handle superfile with multiple subfiles
  2749. File->setBrowseData(false);
  2750. else
  2751. File->setBrowseData(true);
  2752. if (version > 1.13)
  2753. {
  2754. bool bKeyFile = false;
  2755. const char * kind = attr.queryProp("@kind");
  2756. if (kind && (stricmp(kind, "key") == 0))
  2757. {
  2758. bKeyFile = true;
  2759. }
  2760. if (version < 1.24)
  2761. File->setIsKeyFile(bKeyFile);
  2762. else if (kind && *kind)
  2763. File->setContentType(kind);
  2764. }
  2765. StringBuffer buf;
  2766. buf << comma(size);
  2767. File->setTotalsize(buf.str());
  2768. char temp[64];
  2769. numtostr(temp, size);
  2770. File->setLongSize(temp);
  2771. numtostr(temp, records);
  2772. File->setLongRecordCount(temp);
  2773. if (records > 0)
  2774. File->setRecordCount((buf.clear()<<comma(records)).str());
  2775. if (addToPos < 0)
  2776. LogicalFileList.append(*File.getClear());
  2777. else
  2778. LogicalFileList.add(*File.getClear(), (int) addToPos);
  2779. if (LogicalFileList.length() > displayEnd)
  2780. LogicalFileList.pop();
  2781. }
  2782. }
  2783. catch(IException* e)
  2784. {
  2785. VStringBuffer msg("Failed to retrieve data for logical file %s: ", logicalName);
  2786. int code = e->errorCode();
  2787. e->errorMessage(msg);
  2788. e->Release();
  2789. throw MakeStringException(code, "%s", msg.str());
  2790. }
  2791. }
  2792. if (displayEnd > LogicalFileList.length())
  2793. displayEnd = LogicalFileList.length();
  2794. for (int i = (int) displayStart; i < (int) displayEnd; i++)
  2795. {
  2796. Owned<IEspDFULogicalFile> File = createDFULogicalFile("","");
  2797. IEspDFULogicalFile& File0 = LogicalFileList.item(i);
  2798. File->copy(File0);
  2799. LogicalFiles.append(*File.getClear());
  2800. }
  2801. resp.setNumFiles(totalFiles);
  2802. resp.setPageSize(pagesize);
  2803. resp.setPageStartFrom(displayStart+1);
  2804. resp.setPageEndAt(displayEnd);
  2805. if (displayStart - pagesize > 0)
  2806. resp.setPrevPageFrom(displayStart - pagesize + 1);
  2807. else if(displayStart > 0)
  2808. resp.setPrevPageFrom(1);
  2809. if(displayEnd < totalFiles)
  2810. {
  2811. resp.setNextPageFrom(displayEnd+1);
  2812. resp.setLastPageFrom((int)(pagesize * floor((double) ((totalFiles-1) / pagesize)) + 1));
  2813. }
  2814. StringBuffer basicQuery;
  2815. if (req.getNodeGroup() && *req.getNodeGroup())
  2816. {
  2817. if (version < 1.26)
  2818. resp.setClusterName(req.getNodeGroup());
  2819. else
  2820. resp.setNodeGroup(req.getNodeGroup());
  2821. addToQueryString(basicQuery, "NodeGroup", req.getNodeGroup());
  2822. }
  2823. if (req.getOwner() && *req.getOwner())
  2824. {
  2825. resp.setOwner(req.getOwner());
  2826. addToQueryString(basicQuery, "Owner", req.getOwner());
  2827. }
  2828. if (req.getPrefix() && *req.getPrefix())
  2829. {
  2830. resp.setPrefix(req.getPrefix());
  2831. addToQueryString(basicQuery, "Prefix", req.getPrefix());
  2832. }
  2833. if (req.getLogicalName() && *req.getLogicalName())
  2834. {
  2835. resp.setLogicalName(req.getLogicalName());
  2836. addToQueryString(basicQuery, "LogicalName", req.getLogicalName());
  2837. }
  2838. if (req.getStartDate() && *req.getStartDate())
  2839. {
  2840. resp.setStartDate(req.getStartDate());
  2841. addToQueryString(basicQuery, "StartDate", req.getStartDate());
  2842. }
  2843. if (req.getEndDate() && *req.getEndDate())
  2844. {
  2845. resp.setEndDate(req.getEndDate());
  2846. addToQueryString(basicQuery, "EndDate", req.getEndDate());
  2847. }
  2848. if (req.getFileType() && *req.getFileType())
  2849. {
  2850. resp.setFileType(req.getFileType());
  2851. addToQueryString(basicQuery, "FileType", req.getFileType());
  2852. }
  2853. if (req.getFileSizeFrom())
  2854. {
  2855. resp.setFileSizeFrom(req.getFileSizeFrom());
  2856. addToQueryStringFromInt(basicQuery, "FileSizeFrom", req.getFileSizeFrom());
  2857. }
  2858. if (req.getFileSizeTo())
  2859. {
  2860. resp.setFileSizeTo(req.getFileSizeTo());
  2861. addToQueryStringFromInt(basicQuery, "FileSizeTo", req.getFileSizeTo());
  2862. }
  2863. StringBuffer ParametersForFilters = basicQuery;
  2864. StringBuffer ParametersForPaging = basicQuery;
  2865. addToQueryStringFromInt(ParametersForFilters, "PageSize",pagesize);
  2866. addToQueryStringFromInt(ParametersForPaging, "PageSize", pagesize);
  2867. if (ParametersForFilters.length() > 0)
  2868. resp.setFilters(ParametersForFilters.str());
  2869. sortBy.clear();
  2870. descending = false;
  2871. if ((req.getFirstN() > 0) && req.getFirstNType() && *req.getFirstNType())
  2872. {
  2873. const char *sFirstNType = req.getFirstNType();
  2874. if (!stricmp(sFirstNType, "newest"))
  2875. {
  2876. sortBy.set("Modified");
  2877. descending = true;
  2878. }
  2879. else if (!stricmp(sFirstNType, "oldest"))
  2880. {
  2881. sortBy.set("Modified");
  2882. descending = false;
  2883. }
  2884. else if (!stricmp(sFirstNType, "largest"))
  2885. {
  2886. sortBy.set("FileSize");
  2887. descending = true;
  2888. }
  2889. else if (!stricmp(sFirstNType, "smallest"))
  2890. {
  2891. sortBy.set("FileSize");
  2892. descending = false;
  2893. }
  2894. }
  2895. else if (req.getSortby() && *req.getSortby())
  2896. {
  2897. sortBy.set(req.getSortby());
  2898. if (req.getDescending())
  2899. descending = req.getDescending();
  2900. }
  2901. if (sortBy.length())
  2902. {
  2903. resp.setSortby(sortBy);
  2904. resp.setDescending(descending);
  2905. StringBuffer strbuf = sortBy;
  2906. strbuf.append("=");
  2907. String str1(strbuf.str());
  2908. String str(basicQuery.str());
  2909. if (str.indexOf(str1) < 0)
  2910. {
  2911. addToQueryString(ParametersForPaging, "Sortby", sortBy);
  2912. addToQueryString(basicQuery, "Sortby", sortBy);
  2913. if (descending)
  2914. {
  2915. addToQueryString(ParametersForPaging, "Descending", "1");
  2916. addToQueryString(basicQuery, "Descending", "1");
  2917. }
  2918. }
  2919. }
  2920. if (basicQuery.length() > 0)
  2921. resp.setBasicQuery(basicQuery.str());
  2922. if (ParametersForPaging.length() > 0)
  2923. resp.setParametersForPaging(ParametersForPaging.str());
  2924. resp.setDFULogicalFiles(LogicalFiles);
  2925. return;
  2926. }
  2927. bool CWsDfuEx::addDFUQueryFilter(DFUQResultField *filters, unsigned short &count, MemoryBuffer &buff, const char* value, DFUQResultField name)
  2928. {
  2929. if (!value || !*value)
  2930. return false;
  2931. filters[count++] = name;
  2932. buff.append(value);
  2933. return true;
  2934. }
  2935. void CWsDfuEx::appendDFUQueryFilter(const char *name, DFUQFilterType type, const char *value, StringBuffer& filterBuf)
  2936. {
  2937. if (!name || !*name || !value || !*value)
  2938. return;
  2939. filterBuf.append(type).append(DFUQFilterSeparator).append(name).append(DFUQFilterSeparator).append(value).append(DFUQFilterSeparator);
  2940. }
  2941. void CWsDfuEx::appendDFUQueryFilter(const char *name, DFUQFilterType type, const char *value, const char *valueHigh, StringBuffer& filterBuf)
  2942. {
  2943. if (!name || !*name || !value || !*value)
  2944. return;
  2945. filterBuf.append(type).append(DFUQFilterSeparator).append(name).append(DFUQFilterSeparator).append(value).append(DFUQFilterSeparator);
  2946. filterBuf.append(valueHigh).append(DFUQFilterSeparator);
  2947. }
  2948. void CWsDfuEx::setFileTypeFilter(const char* fileType, StringBuffer& filterBuf)
  2949. {
  2950. DFUQFileTypeFilter fileTypeFilter = DFUQFFTall;
  2951. if (!fileType || !*fileType)
  2952. {
  2953. filterBuf.append(DFUQFTspecial).append(DFUQFilterSeparator).append(DFUQSFFileType).append(DFUQFilterSeparator).append(fileTypeFilter).append(DFUQFilterSeparator);
  2954. return;
  2955. }
  2956. bool notInSuperfile = false;
  2957. if (strieq(fileType, "Superfiles Only"))
  2958. fileTypeFilter = DFUQFFTsuperfileonly;
  2959. else if (strieq(fileType, "Logical Files Only"))
  2960. fileTypeFilter = DFUQFFTnonsuperfileonly;
  2961. else if (strieq(fileType, "Not in Superfiles"))
  2962. notInSuperfile = true;
  2963. else
  2964. fileTypeFilter = DFUQFFTall;
  2965. filterBuf.append(DFUQFTspecial).append(DFUQFilterSeparator).append(DFUQSFFileType).append(DFUQFilterSeparator).append(fileTypeFilter).append(DFUQFilterSeparator);
  2966. if (notInSuperfile)
  2967. appendDFUQueryFilter(getDFUQFilterFieldName(DFUQFFsuperowner), DFUQFThasProp, "0", filterBuf);
  2968. }
  2969. void CWsDfuEx::setFileNameFilter(const char* fname, const char* prefix, StringBuffer &filterBuf)
  2970. {
  2971. StringBuffer fileNameFilter;
  2972. if(fname && *fname)
  2973. fileNameFilter.append(fname);//ex. *part_of_file_name*
  2974. else
  2975. {
  2976. if(prefix && *prefix)
  2977. {
  2978. fileNameFilter.append(prefix);
  2979. fileNameFilter.append("::");
  2980. }
  2981. fileNameFilter.append("*");
  2982. }
  2983. fileNameFilter.toLowerCase();
  2984. filterBuf.append(DFUQFTspecial).append(DFUQFilterSeparator).append(DFUQSFFileNameWithPrefix).append(DFUQFilterSeparator).append(fileNameFilter.str()).append(DFUQFilterSeparator);
  2985. }
  2986. void CWsDfuEx::setFileIterateFilter(unsigned maxFiles, StringBuffer &filterBuf)
  2987. {
  2988. filterBuf.append(DFUQFTspecial).append(DFUQFilterSeparator).append(DFUQSFMaxFiles).append(DFUQFilterSeparator)
  2989. .append(maxFiles).append(DFUQFilterSeparator);
  2990. }
  2991. void CWsDfuEx::setDFUQueryFilters(IEspDFUQueryRequest& req, StringBuffer& filterBuf)
  2992. {
  2993. setFileNameFilter(req.getLogicalName(), req.getPrefix(), filterBuf);
  2994. setFileTypeFilter(req.getFileType(), filterBuf);
  2995. appendDFUQueryFilter(getDFUQFilterFieldName(DFUQFFattrowner), DFUQFTwildcardMatch, req.getOwner(), filterBuf);
  2996. appendDFUQueryFilter(getDFUQFilterFieldName(DFUQFFkind), DFUQFTwildcardMatch, req.getContentType(), filterBuf);
  2997. appendDFUQueryFilter(getDFUQFilterFieldName(DFUQFFgroup), DFUQFTcontainString, req.getNodeGroup(), ",", filterBuf);
  2998. if (!req.getIncludeSuperOwner_isNull() && req.getIncludeSuperOwner())
  2999. filterBuf.append(DFUQFTincludeFileAttr).append(DFUQFilterSeparator).append(DFUQSFAOincludeSuperOwner).append(DFUQFilterSeparator);
  3000. __int64 sizeFrom = req.getFileSizeFrom();
  3001. __int64 sizeTo = req.getFileSizeTo();
  3002. if ((sizeFrom > 0) || (sizeTo > 0))
  3003. {
  3004. StringBuffer buf;
  3005. if (sizeFrom > 0)
  3006. buf.append(sizeFrom);
  3007. buf.append("|");
  3008. if (sizeTo > 0)
  3009. buf.append(sizeTo);
  3010. filterBuf.append(DFUQFTinteger64Range).append(DFUQFilterSeparator).append(getDFUQFilterFieldName(DFUQFFattrsize));
  3011. filterBuf.append(DFUQFilterSeparator).append(buf.str()).append(DFUQFilterSeparator);
  3012. }
  3013. const char* startDate = req.getStartDate();
  3014. const char* endDate = req.getEndDate();
  3015. if((startDate && *startDate) || (endDate && *endDate))
  3016. {
  3017. StringBuffer buf;
  3018. if(startDate && *startDate)
  3019. {
  3020. StringBuffer wuFrom;
  3021. CDateTime wuTime;
  3022. wuTime.setString(startDate,NULL);
  3023. buf.append(wuTime.getString(wuFrom).str());
  3024. }
  3025. buf.append("|");
  3026. if(endDate && *endDate)
  3027. {
  3028. StringBuffer wuTo;
  3029. CDateTime wuTime;
  3030. wuTime.setString(endDate,NULL);
  3031. buf.append(wuTime.getString(wuTo).str());
  3032. }
  3033. filterBuf.append(DFUQFTstringRange).append(DFUQFilterSeparator).append(getDFUQFilterFieldName(DFUQFFtimemodified));
  3034. filterBuf.append(DFUQFilterSeparator).append(buf.str()).append(DFUQFilterSeparator);
  3035. }
  3036. }
  3037. void CWsDfuEx::setDFUQuerySortOrder(IEspDFUQueryRequest& req, StringBuffer& sortBy, bool& descending, DFUQResultField* sortOrder)
  3038. {
  3039. const char* sortByReq = req.getSortby();
  3040. if (!sortByReq || !*sortByReq)
  3041. return;
  3042. sortBy.set(sortByReq);
  3043. if (req.getDescending())
  3044. descending = req.getDescending();
  3045. const char* sortByPtr = sortBy.str();
  3046. if (strieq(sortByPtr, "FileSize"))
  3047. sortOrder[0] = (DFUQResultField) (DFUQRFsize | DFUQRFnumeric);
  3048. else if (strieq(sortByPtr, "IsCompressed"))
  3049. sortOrder[0] = (DFUQResultField) (DFUQRFiscompressed | DFUQRFnumeric);
  3050. else if (strieq(sortByPtr, "CompressedSize"))
  3051. sortOrder[0] = (DFUQResultField) (DFUQRFcompressedsize | DFUQRFnumeric);
  3052. else if (strieq(sortByPtr, "Parts"))
  3053. sortOrder[0] = (DFUQResultField) (DFUQRFnumparts | DFUQRFnumeric);
  3054. else if (strieq(sortByPtr, "Records"))
  3055. sortOrder[0] = (DFUQResultField) (DFUQRFrecordcount | DFUQRFnumeric);
  3056. else if (strieq(sortByPtr, "Owner"))
  3057. sortOrder[0] = DFUQRFowner;
  3058. else if (strieq(sortByPtr, "NodeGroup"))
  3059. sortOrder[0] = DFUQRFnodegroup;
  3060. else if (strieq(sortByPtr, "Modified"))
  3061. sortOrder[0] = DFUQRFtimemodified;
  3062. else if (strieq(sortByPtr, "ContentType"))
  3063. sortOrder[0] = DFUQRFkind;
  3064. else
  3065. sortOrder[0] = DFUQRFname;
  3066. sortOrder[0] = (DFUQResultField) (sortOrder[0] | DFUQRFnocase);
  3067. if (descending)
  3068. sortOrder[0] = (DFUQResultField) (sortOrder[0] | DFUQRFreverse);
  3069. return;
  3070. }
  3071. const char* CWsDfuEx::getPrefixFromLogicalName(const char* logicalName, StringBuffer& prefix)
  3072. {
  3073. if (!logicalName || !*logicalName)
  3074. return NULL;
  3075. const char *c=strstr(logicalName, "::");
  3076. if (c)
  3077. prefix.append(c-logicalName, logicalName);
  3078. else
  3079. prefix.append(logicalName);
  3080. return prefix.str();
  3081. }
  3082. bool CWsDfuEx::addToLogicalFileList(IPropertyTree& file, const char* nodeGroup, double version, IArrayOf<IEspDFULogicalFile>& logicalFiles)
  3083. {
  3084. const char* logicalName = file.queryProp(getDFUQResultFieldName(DFUQRFname));
  3085. if (!logicalName || !*logicalName)
  3086. return false;
  3087. try
  3088. {
  3089. Owned<IEspDFULogicalFile> lFile = createDFULogicalFile("","");
  3090. lFile->setName(logicalName);
  3091. lFile->setOwner(file.queryProp(getDFUQResultFieldName(DFUQRFowner)));
  3092. StringBuffer buf(file.queryProp(getDFUQResultFieldName(DFUQRFtimemodified)));
  3093. lFile->setModified(buf.replace('T', ' ').str());
  3094. lFile->setPrefix(getPrefixFromLogicalName(logicalName, buf.clear()));
  3095. lFile->setDescription(file.queryProp(getDFUQResultFieldName(DFUQRFdescription)));
  3096. if (!nodeGroup || !*nodeGroup)
  3097. nodeGroup = file.queryProp(getDFUQResultFieldName(DFUQRFnodegroup));
  3098. if (nodeGroup && *nodeGroup)
  3099. {
  3100. if (version < 1.26)
  3101. lFile->setClusterName(nodeGroup);
  3102. else
  3103. lFile->setNodeGroup(nodeGroup);
  3104. }
  3105. int numSubFiles = file.hasProp(getDFUQResultFieldName(DFUQRFnumsubfiles));
  3106. if(numSubFiles)
  3107. lFile->setIsSuperfile(true);
  3108. else
  3109. {
  3110. lFile->setIsSuperfile(false);
  3111. lFile->setDirectory(file.queryProp(getDFUQResultFieldName(DFUQRFdirectory)));
  3112. lFile->setParts(file.queryProp(getDFUQResultFieldName(DFUQRFnumparts)));
  3113. }
  3114. lFile->setBrowseData(numSubFiles > 1 ? false : true); ////Bug 41379 - ViewKeyFile Cannot handle superfile with multiple subfiles
  3115. if (version >= 1.30)
  3116. {
  3117. bool persistent = file.getPropBool(getDFUQResultFieldName(DFUQRFpersistent), false);
  3118. if (persistent)
  3119. lFile->setPersistent(true);
  3120. if (file.hasProp(getDFUQResultFieldName(DFUQRFsuperowners)))
  3121. lFile->setSuperOwners(file.queryProp(getDFUQResultFieldName(DFUQRFsuperowners)));
  3122. if (file.hasProp(getDFUQResultFieldName(DFUQRFprotect)))
  3123. lFile->setIsProtected(true);
  3124. }
  3125. __int64 size = file.getPropInt64(getDFUQResultFieldName(DFUQRForigsize),0);
  3126. if (size > 0)
  3127. {
  3128. lFile->setIntSize(size);
  3129. lFile->setTotalsize((buf.clear()<<comma(size)).str());
  3130. }
  3131. __int64 records = file.getPropInt64(getDFUQResultFieldName(DFUQRFrecordcount),0);
  3132. if (!records)
  3133. records = file.getPropInt64(getDFUQResultFieldName(DFUQRForigrecordcount),0);
  3134. if (!records)
  3135. {
  3136. __int64 recordSize=file.getPropInt64(getDFUQResultFieldName(DFUQRFrecordsize),0);
  3137. if(recordSize > 0)
  3138. records = size/recordSize;
  3139. }
  3140. if (records > 0)
  3141. {
  3142. lFile->setIntRecordCount(records);
  3143. lFile->setRecordCount((buf.clear()<<comma(records)).str());
  3144. }
  3145. bool isKeyFile = false;
  3146. if (version > 1.13)
  3147. {
  3148. const char * kind = file.queryProp(getDFUQResultFieldName(DFUQRFkind));
  3149. if (kind && *kind)
  3150. {
  3151. if (strieq(kind, "key"))
  3152. isKeyFile = true;
  3153. if (version >= 1.24)
  3154. lFile->setContentType(kind);
  3155. else
  3156. lFile->setIsKeyFile(isKeyFile);
  3157. }
  3158. }
  3159. bool isFileCompressed = file.getPropBool(getDFUQResultFieldName(DFUQRFiscompressed));
  3160. if (isFileCompressed)
  3161. {
  3162. if (version >= 1.22)
  3163. {
  3164. if (file.hasProp(getDFUQResultFieldName(DFUQRFcompressedsize)))
  3165. lFile->setCompressedFileSize(file.getPropInt64(getDFUQResultFieldName(DFUQRFcompressedsize)));
  3166. else if (isKeyFile)
  3167. lFile->setCompressedFileSize(size);
  3168. }
  3169. }
  3170. if (version < 1.22)
  3171. lFile->setIsZipfile(isFileCompressed);
  3172. else
  3173. lFile->setIsCompressed(isFileCompressed);
  3174. logicalFiles.append(*lFile.getClear());
  3175. }
  3176. catch(IException* e)
  3177. {
  3178. VStringBuffer msg("Failed to retrieve data for logical file %s: ", logicalName);
  3179. int code = e->errorCode();
  3180. e->errorMessage(msg);
  3181. e->Release();
  3182. throw MakeStringException(code, "%s", msg.str());
  3183. }
  3184. return true;
  3185. }
  3186. void CWsDfuEx::setDFUQueryResponse(IEspContext &context, unsigned totalFiles, StringBuffer& sortBy, bool descending, unsigned pageStart, unsigned pageSize,
  3187. IEspDFUQueryRequest& req, IEspDFUQueryResponse& resp)
  3188. {
  3189. //for legacy
  3190. double version = context.getClientVersion();
  3191. unsigned pageEnd = pageStart + pageSize;
  3192. if (pageEnd > totalFiles)
  3193. pageEnd = totalFiles;
  3194. resp.setNumFiles(totalFiles);
  3195. resp.setPageSize(pageSize);
  3196. resp.setPageStartFrom(pageStart+1);
  3197. resp.setPageEndAt(pageEnd);
  3198. if (pageStart > pageSize)
  3199. resp.setPrevPageFrom(pageStart - pageSize + 1);
  3200. else if(pageStart > 0)
  3201. resp.setPrevPageFrom(1);
  3202. if(pageEnd < totalFiles)
  3203. {
  3204. resp.setNextPageFrom(pageEnd+1);
  3205. resp.setLastPageFrom((int)(pageSize * floor((double) ((totalFiles-1) / pageSize)) + 1));
  3206. }
  3207. StringBuffer queryReq;
  3208. if (req.getNodeGroup() && *req.getNodeGroup())
  3209. {
  3210. if (version < 1.26)
  3211. resp.setClusterName(req.getNodeGroup());
  3212. else
  3213. resp.setNodeGroup(req.getNodeGroup());
  3214. addToQueryString(queryReq, "NodeGroup", req.getNodeGroup());
  3215. }
  3216. if (req.getOwner() && *req.getOwner())
  3217. {
  3218. resp.setOwner(req.getOwner());
  3219. addToQueryString(queryReq, "Owner", req.getOwner());
  3220. }
  3221. if (req.getPrefix() && *req.getPrefix())
  3222. {
  3223. resp.setPrefix(req.getPrefix());
  3224. addToQueryString(queryReq, "Prefix", req.getPrefix());
  3225. }
  3226. if (req.getLogicalName() && *req.getLogicalName())
  3227. {
  3228. resp.setLogicalName(req.getLogicalName());
  3229. addToQueryString(queryReq, "LogicalName", req.getLogicalName());
  3230. }
  3231. if (req.getStartDate() && *req.getStartDate())
  3232. {
  3233. resp.setStartDate(req.getStartDate());
  3234. addToQueryString(queryReq, "StartDate", req.getStartDate());
  3235. }
  3236. if (req.getEndDate() && *req.getEndDate())
  3237. {
  3238. resp.setEndDate(req.getEndDate());
  3239. addToQueryString(queryReq, "EndDate", req.getEndDate());
  3240. }
  3241. if (req.getFileType() && *req.getFileType())
  3242. {
  3243. resp.setFileType(req.getFileType());
  3244. addToQueryString(queryReq, "FileType", req.getFileType());
  3245. }
  3246. if (req.getFileSizeFrom())
  3247. {
  3248. resp.setFileSizeFrom(req.getFileSizeFrom());
  3249. addToQueryStringFromInt(queryReq, "FileSizeFrom", req.getFileSizeFrom());
  3250. }
  3251. if (req.getFileSizeTo())
  3252. {
  3253. resp.setFileSizeTo(req.getFileSizeTo());
  3254. addToQueryStringFromInt(queryReq, "FileSizeTo", req.getFileSizeTo());
  3255. }
  3256. StringBuffer queryReqNoPageSize = queryReq;
  3257. addToQueryStringFromInt(queryReq, "PageSize", pageSize);
  3258. resp.setFilters(queryReq.str());
  3259. if (sortBy.length())
  3260. {
  3261. resp.setSortby(sortBy.str());
  3262. resp.setDescending(descending);
  3263. addToQueryString(queryReq, "Sortby", sortBy.str());
  3264. addToQueryString(queryReqNoPageSize, "Sortby", sortBy.str());
  3265. if (descending)
  3266. {
  3267. addToQueryString(queryReq, "Descending", "1");
  3268. addToQueryString(queryReqNoPageSize, "Descending", "1");
  3269. }
  3270. }
  3271. resp.setBasicQuery(queryReqNoPageSize.str());
  3272. resp.setParametersForPaging(queryReq.str());
  3273. return;
  3274. }
  3275. bool CWsDfuEx::doLogicalFileSearch(IEspContext &context, IUserDescriptor* udesc, IEspDFUQueryRequest & req, IEspDFUQueryResponse & resp)
  3276. {
  3277. double version = context.getClientVersion();
  3278. if (req.getOneLevelDirFileReturn())
  3279. {
  3280. int numDirs = 0;
  3281. int numFiles = 0;
  3282. IArrayOf<IEspDFULogicalFile> logicalFiles;
  3283. getLogicalFileAndDirectory(context, udesc, req.getLogicalName(), !req.getIncludeSuperOwner_isNull() && req.getIncludeSuperOwner(), logicalFiles, numFiles, numDirs);
  3284. return true;
  3285. }
  3286. if (queryDaliServerVersion().compare("3.11") < 0)
  3287. {//Dali server does not support Filtered File Query. Use legacy code.
  3288. PROGLOG("DFUQuery: getAPageOfSortedLogicalFile");
  3289. getAPageOfSortedLogicalFile(context, udesc, req, resp);
  3290. return true;
  3291. }
  3292. StringBuffer filterBuf;
  3293. setDFUQueryFilters(req, filterBuf);
  3294. //Now, set filters which are used to filter query result received from dali server.
  3295. unsigned short localFilterCount = 0;
  3296. DFUQResultField localFilters[8];
  3297. MemoryBuffer localFilterBuf;
  3298. addDFUQueryFilter(localFilters, localFilterCount, localFilterBuf, req.getNodeGroup(), DFUQRFnodegroup);
  3299. localFilters[localFilterCount] = DFUQRFterm;
  3300. StringBuffer sortBy;
  3301. bool descending = false;
  3302. DFUQResultField sortOrder[2] = {DFUQRFname, DFUQRFterm};
  3303. setDFUQuerySortOrder(req, sortBy, descending, sortOrder);
  3304. unsigned pageStart = 0;
  3305. if (req.getPageStartFrom() > 0)
  3306. pageStart = req.getPageStartFrom() - 1;
  3307. unsigned pageSize = req.getPageSize();
  3308. if (pageSize < 1)
  3309. pageSize = 100;
  3310. const int firstN = req.getFirstN();
  3311. if (firstN > 0)
  3312. {
  3313. pageStart = 0;
  3314. pageSize = firstN;
  3315. }
  3316. unsigned maxFiles = 0;
  3317. if(!req.getMaxNumberOfFiles_isNull())
  3318. maxFiles = req.getMaxNumberOfFiles();
  3319. if (maxFiles == 0)
  3320. maxFiles = ITERATE_FILTEREDFILES_LIMIT;
  3321. if (maxFiles != ITERATE_FILTEREDFILES_LIMIT)
  3322. setFileIterateFilter(maxFiles, filterBuf);
  3323. __int64 cacheHint = 0;
  3324. if (!req.getCacheHint_isNull())
  3325. cacheHint = req.getCacheHint();
  3326. bool allMatchingFilesReceived = true;
  3327. unsigned totalFiles = 0;
  3328. PROGLOG("DFUQuery: getLogicalFilesSorted");
  3329. Owned<IDFAttributesIterator> it = queryDistributedFileDirectory().getLogicalFilesSorted(udesc, sortOrder, filterBuf.str(),
  3330. localFilters, localFilterBuf.bufferBase(), pageStart, pageSize, &cacheHint, &totalFiles, &allMatchingFilesReceived);
  3331. if(!it)
  3332. throw MakeStringException(ECLWATCH_CANNOT_GET_FILE_ITERATOR,"Cannot get information from file system.");
  3333. PROGLOG("DFUQuery: getLogicalFilesSorted done");
  3334. IArrayOf<IEspDFULogicalFile> logicalFiles;
  3335. ForEach(*it)
  3336. addToLogicalFileList(it->query(), NULL, version, logicalFiles);
  3337. if (!allMatchingFilesReceived)
  3338. {
  3339. VStringBuffer warning("The returned results (%d files) represent a subset of the total number of matches. Using a correct filter may reduce the number of matches.",
  3340. maxFiles);
  3341. resp.setWarning(warning.str());
  3342. resp.setIsSubsetOfFiles(!allMatchingFilesReceived);
  3343. }
  3344. resp.setCacheHint(cacheHint);
  3345. resp.setDFULogicalFiles(logicalFiles);
  3346. setDFUQueryResponse(context, totalFiles, sortBy, descending, pageStart, pageSize, req, resp); //This call may be removed after 5.0
  3347. return true;
  3348. }
  3349. bool CWsDfuEx::onSuperfileList(IEspContext &context, IEspSuperfileListRequest &req, IEspSuperfileListResponse &resp)
  3350. {
  3351. try
  3352. {
  3353. const char* superfile = req.getSuperfile();
  3354. if (!superfile || !*superfile)
  3355. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Superfile name required");
  3356. PROGLOG("SuperfileList: %s", superfile);
  3357. StringBuffer username;
  3358. context.getUserID(username);
  3359. Owned<IUserDescriptor> userdesc;
  3360. if(username.length() > 0)
  3361. {
  3362. userdesc.setown(createUserDescriptor());
  3363. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  3364. }
  3365. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  3366. StringArray farray;
  3367. StringAttrArray subfiles;
  3368. dfuhelper->listSubFiles(req.getSuperfile(), subfiles, userdesc.get());
  3369. for(unsigned i = 0; i < subfiles.length(); i++)
  3370. {
  3371. StringAttrItem& subfile = subfiles.item(i);
  3372. farray.append(subfile.text);
  3373. }
  3374. if(farray.length() > 0)
  3375. resp.setSubfiles(farray);
  3376. resp.setSuperfile(req.getSuperfile());
  3377. }
  3378. catch(IException* e)
  3379. {
  3380. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3381. }
  3382. return true;
  3383. }
  3384. bool CWsDfuEx::onSuperfileAction(IEspContext &context, IEspSuperfileActionRequest &req, IEspSuperfileActionResponse &resp)
  3385. {
  3386. try
  3387. {
  3388. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Write, false))
  3389. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to Superfile action. Permission denied.");
  3390. const char* action = req.getAction();
  3391. const char* superfile = req.getSuperfile();
  3392. superfileAction(context, action, superfile, req.getSubfiles(), req.getBefore(), true, true, req.getDelete(), req.getRemoveSuperfile());
  3393. resp.setRetcode(0);
  3394. if (superfile && *superfile && action && strieq(action, "remove"))
  3395. {
  3396. Owned<IUserDescriptor> udesc;
  3397. udesc.setown(createUserDescriptor());
  3398. udesc->set(context.queryUserId(), context.queryPassword(), context.querySignature());
  3399. Owned<IDistributedSuperFile> fp = queryDistributedFileDirectory().lookupSuperFile(superfile,udesc);
  3400. if (!fp)
  3401. resp.setRetcode(-1); //Superfile has been removed.
  3402. }
  3403. resp.setSuperfile(req.getSuperfile());
  3404. }
  3405. catch(IException* e)
  3406. {
  3407. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3408. }
  3409. return true;
  3410. }
  3411. bool CWsDfuEx::onSavexml(IEspContext &context, IEspSavexmlRequest &req, IEspSavexmlResponse &resp)
  3412. {
  3413. try
  3414. {
  3415. StringBuffer username;
  3416. context.getUserID(username);
  3417. Owned<IUserDescriptor> userdesc;
  3418. if(username.length() > 0)
  3419. {
  3420. userdesc.setown(createUserDescriptor());
  3421. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  3422. }
  3423. if (!req.getName() || !*req.getName())
  3424. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Name required");
  3425. PROGLOG("getFileXML: %s", req.getName());
  3426. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  3427. StringBuffer out;
  3428. dfuhelper->getFileXML(req.getName(), out, userdesc.get());
  3429. MemoryBuffer xmlmap;
  3430. int len = out.length();
  3431. xmlmap.setBuffer(len, out.detach(), true);
  3432. resp.setXmlmap(xmlmap);
  3433. }
  3434. catch(IException* e)
  3435. {
  3436. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3437. }
  3438. return true;
  3439. }
  3440. bool CWsDfuEx::onAdd(IEspContext &context, IEspAddRequest &req, IEspAddResponse &resp)
  3441. {
  3442. try
  3443. {
  3444. StringBuffer username;
  3445. context.getUserID(username);
  3446. Owned<IUserDescriptor> userdesc;
  3447. if(username.length() > 0)
  3448. {
  3449. userdesc.setown(createUserDescriptor());
  3450. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  3451. }
  3452. if (!req.getDstname() || !*req.getDstname())
  3453. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Dstname required.");
  3454. PROGLOG("addFileXML: %s", req.getDstname());
  3455. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  3456. StringBuffer xmlstr(req.getXmlmap().length(),(const char*)req.getXmlmap().bufferBase());
  3457. dfuhelper->addFileXML(req.getDstname(), xmlstr, userdesc.get());
  3458. }
  3459. catch(IException* e)
  3460. {
  3461. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3462. }
  3463. return true;
  3464. }
  3465. bool CWsDfuEx::onAddRemote(IEspContext &context, IEspAddRemoteRequest &req, IEspAddRemoteResponse &resp)
  3466. {
  3467. try
  3468. {
  3469. StringBuffer username;
  3470. context.getUserID(username);
  3471. Owned<IUserDescriptor> userdesc;
  3472. if(username.length() > 0)
  3473. {
  3474. userdesc.setown(createUserDescriptor());
  3475. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  3476. }
  3477. const char* srcusername = req.getSrcusername();
  3478. Owned<IUserDescriptor> srcuserdesc;
  3479. if(srcusername && *srcusername)
  3480. {
  3481. srcuserdesc.setown(createUserDescriptor());
  3482. srcuserdesc->set(srcusername, req.getSrcpassword(), context.querySignature());
  3483. }
  3484. const char* srcname = req.getSrcname();
  3485. if(srcname == NULL || *srcname == '\0')
  3486. throw MakeStringException(ECLWATCH_INVALID_INPUT, "srcname can't be empty.");
  3487. const char* srcdali = req.getSrcdali();
  3488. if(srcdali == NULL || *srcdali == '\0')
  3489. throw MakeStringException(ECLWATCH_INVALID_INPUT, "srcdali can't be empty.");
  3490. const char* dstname = req.getDstname();
  3491. if(dstname == NULL || *dstname == '\0')
  3492. throw MakeStringException(ECLWATCH_INVALID_INPUT, "dstname can't be empty.");
  3493. PROGLOG("addFileRemote: Srcdali %s, Srcname %s, Dstname %s", srcdali, srcname, dstname);
  3494. SocketEndpoint ep(srcdali);
  3495. Owned<IDFUhelper> dfuhelper = createIDFUhelper();
  3496. dfuhelper->addFileRemote(dstname, ep, srcname, srcuserdesc.get(), userdesc.get());
  3497. }
  3498. catch(IException* e)
  3499. {
  3500. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3501. }
  3502. return true;
  3503. }
  3504. const int INTEGELSIZE = 20;
  3505. const int REALSIZE = 32;
  3506. const int STRINGSIZE = 128;
  3507. bool CWsDfuEx::onDFUGetDataColumns(IEspContext &context, IEspDFUGetDataColumnsRequest &req, IEspDFUGetDataColumnsResponse &resp)
  3508. {
  3509. try
  3510. {
  3511. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  3512. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to View Data File. Permission denied.");
  3513. StringBuffer logicalNameStr;
  3514. char* logicalName0 = (char*) req.getOpenLogicalName();
  3515. if (logicalName0 && *logicalName0)
  3516. {
  3517. logicalNameStr.append(logicalName0);
  3518. logicalNameStr.trim();
  3519. }
  3520. if (logicalNameStr.length() > 0)
  3521. {
  3522. PROGLOG("DFUGetDataColumns: %s", logicalNameStr.str());
  3523. __int64 startIndex = req.getStartIndex();
  3524. __int64 endIndex = req.getEndIndex();
  3525. if (startIndex < 1)
  3526. startIndex = 1;
  3527. if (endIndex < 1)
  3528. endIndex = 100;
  3529. StringArray filterByNames, filterByValues;
  3530. double version = context.getClientVersion();
  3531. if (version > 1.04)
  3532. {
  3533. const char* filterBy = req.getFilterBy();
  3534. if (filterBy && *filterBy)
  3535. {
  3536. parseTwoStringArrays(filterBy, filterByNames, filterByValues);
  3537. }
  3538. const char* showColumns = req.getShowColumns();
  3539. if (showColumns && *showColumns)
  3540. {
  3541. resp.setShowColumns(showColumns);
  3542. }
  3543. }
  3544. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  3545. Owned<INewResultSet> result;
  3546. if (m_clusterName.length() > 0)
  3547. {
  3548. result.setown(resultSetFactory->createNewFileResultSet(logicalNameStr.str(), m_clusterName.str()));
  3549. }
  3550. else
  3551. {
  3552. result.setown(resultSetFactory->createNewFileResultSet(logicalNameStr.str(), NULL));
  3553. }
  3554. __int64 total=result->getNumRows();
  3555. {
  3556. IArrayOf<IEspDFUDataColumn> dataKeyedColumns[MAX_KEY_ROWS];
  3557. IArrayOf<IEspDFUDataColumn> dataNonKeyedColumns[MAX_KEY_ROWS];
  3558. const IResultSetMetaData & meta = result->getMetaData();
  3559. int columnCount = meta.getColumnCount();
  3560. int keyedColumnCount = meta.getNumKeyedColumns();
  3561. unsigned columnSize = 0;
  3562. int lineSizeCount = 0;
  3563. int lineCount = 0;
  3564. for (int i = 0; i < keyedColumnCount; i++)
  3565. {
  3566. Owned<IEspDFUDataColumn> item = createDFUDataColumn("","");
  3567. bool bNaturalColumn = true;
  3568. SCMStringBuffer columnLabel;
  3569. if (meta.hasSetTranslation(i))
  3570. {
  3571. meta.getNaturalColumnLabel(columnLabel, i);
  3572. }
  3573. if (columnLabel.length() < 1)
  3574. {
  3575. meta.getColumnLabel(columnLabel, i);
  3576. bNaturalColumn = false;
  3577. }
  3578. item->setColumnLabel(columnLabel.str());
  3579. if (version > 1.04 && filterByNames.length() > 0)
  3580. {
  3581. for (unsigned ii = 0; ii < filterByNames.length(); ii++)
  3582. {
  3583. const char* name = filterByNames.item(ii);
  3584. if (name && !stricmp(name, columnLabel.str()))
  3585. {
  3586. const char* value = filterByValues.item(ii);
  3587. if (value && *value)
  3588. {
  3589. item->setColumnValue(value);
  3590. break;
  3591. }
  3592. }
  3593. }
  3594. }
  3595. DisplayType columnType = meta.getColumnDisplayType(i);
  3596. if (bNaturalColumn)
  3597. {
  3598. item->setColumnType("Others");
  3599. item->setColumnSize(STRINGSIZE);
  3600. columnSize = STRINGSIZE;
  3601. item->setMaxSize(columnSize);
  3602. }
  3603. else if (columnType == TypeBoolean)
  3604. {
  3605. item->setColumnType("Boolean");
  3606. item->setMaxSize(1);
  3607. item->setColumnSize(strlen(columnLabel.str()));
  3608. columnSize = 2;
  3609. }
  3610. else
  3611. {
  3612. if (columnType == TypeInteger || columnType == TypeUnsignedInteger)
  3613. {
  3614. item->setColumnType("Integer");
  3615. item->setMaxSize(INTEGELSIZE);
  3616. columnSize = INTEGELSIZE;
  3617. if (strlen(columnLabel.str()) > columnSize)
  3618. columnSize = strlen(columnLabel.str());
  3619. item->setColumnSize(columnSize);
  3620. }
  3621. else if (columnType == TypeReal)
  3622. {
  3623. item->setColumnType("Real");
  3624. item->setMaxSize(REALSIZE);
  3625. columnSize = REALSIZE;
  3626. if (strlen(columnLabel.str()) > columnSize)
  3627. columnSize = strlen(columnLabel.str());
  3628. item->setColumnSize(columnSize);
  3629. }
  3630. else if (columnType == TypeString)
  3631. {
  3632. columnSize = meta.getColumnRawSize(i);
  3633. columnSize = rtlQStrLength(columnSize);
  3634. if (columnSize < 1)
  3635. columnSize = STRINGSIZE;
  3636. else if (columnSize > STRINGSIZE)
  3637. columnSize = STRINGSIZE;
  3638. item->setColumnType("String");
  3639. item->setMaxSize(columnSize);
  3640. if (strlen(columnLabel.str()) > columnSize)
  3641. columnSize = strlen(columnLabel.str());
  3642. item->setColumnSize(columnSize);
  3643. }
  3644. else if (columnType == TypeUnicode)
  3645. {
  3646. item->setColumnType("Others");
  3647. columnSize = (int) (meta.getColumnRawSize(i) * 0.5);
  3648. if (columnSize > STRINGSIZE)
  3649. columnSize = STRINGSIZE;
  3650. item->setColumnSize(columnSize);
  3651. item->setMaxSize(columnSize);
  3652. }
  3653. else
  3654. {
  3655. item->setColumnType("Others");
  3656. columnSize = STRINGSIZE;
  3657. item->setColumnSize(columnSize);
  3658. item->setMaxSize(columnSize);
  3659. }
  3660. }
  3661. columnSize += 7;
  3662. if ((lineSizeCount == 0) && (columnSize > STRINGSIZE)) //One field is big enough to use one line
  3663. {
  3664. if (lineCount >= MAX_KEY_ROWS)
  3665. break;
  3666. dataKeyedColumns[lineCount].append(*item.getLink());
  3667. lineCount++;
  3668. }
  3669. else
  3670. {
  3671. if (lineSizeCount + columnSize < STRINGSIZE)
  3672. {
  3673. lineSizeCount += columnSize;
  3674. }
  3675. else //too big in this line...so, switch to another line
  3676. {
  3677. lineCount++;
  3678. lineSizeCount = columnSize;
  3679. }
  3680. if (lineCount >= MAX_KEY_ROWS)
  3681. break;
  3682. dataKeyedColumns[lineCount].append(*item.getLink());
  3683. }
  3684. }
  3685. columnSize = 0;
  3686. lineSizeCount = 0;
  3687. lineCount = 0;
  3688. for (int ii = keyedColumnCount; ii < columnCount; ii++)
  3689. {
  3690. Owned<IEspDFUDataColumn> item = createDFUDataColumn("","");
  3691. bool bNaturalColumn = true;
  3692. SCMStringBuffer columnLabel;
  3693. if (meta.hasSetTranslation(ii))
  3694. {
  3695. meta.getNaturalColumnLabel(columnLabel, ii);
  3696. }
  3697. if (columnLabel.length() < 1)
  3698. {
  3699. meta.getColumnLabel(columnLabel, ii);
  3700. bNaturalColumn = false;
  3701. }
  3702. item->setColumnLabel(columnLabel.str());
  3703. if (version > 1.04 && filterByNames.length() > 0)
  3704. {
  3705. for (unsigned ii = 0; ii < filterByNames.length(); ii++)
  3706. {
  3707. const char* name = filterByNames.item(ii);
  3708. if (name && !stricmp(name, columnLabel.str()))
  3709. {
  3710. const char* value = filterByValues.item(ii);
  3711. if (value && *value)
  3712. {
  3713. item->setColumnValue(value);
  3714. break;
  3715. }
  3716. }
  3717. }
  3718. }
  3719. DisplayType columnType = meta.getColumnDisplayType(ii);
  3720. if (bNaturalColumn)
  3721. {
  3722. item->setColumnType("Others");
  3723. item->setColumnSize(STRINGSIZE);
  3724. columnSize = STRINGSIZE;
  3725. }
  3726. else if (columnType == TypeBoolean)
  3727. {
  3728. item->setColumnType("Boolean");
  3729. item->setMaxSize(1);
  3730. item->setColumnSize(strlen(columnLabel.str()));
  3731. columnSize = 2;
  3732. }
  3733. else
  3734. {
  3735. if (columnType == TypeInteger || columnType == TypeUnsignedInteger)
  3736. {
  3737. item->setColumnType("Integer");
  3738. item->setMaxSize(INTEGELSIZE);
  3739. columnSize = INTEGELSIZE;
  3740. if (strlen(columnLabel.str()) > columnSize)
  3741. columnSize = strlen(columnLabel.str());
  3742. item->setColumnSize(columnSize);
  3743. }
  3744. else if (columnType == TypeReal)
  3745. {
  3746. item->setColumnType("Real");
  3747. item->setMaxSize(REALSIZE);
  3748. columnSize = REALSIZE;
  3749. if (strlen(columnLabel.str()) > columnSize)
  3750. columnSize = strlen(columnLabel.str());
  3751. item->setColumnSize(columnSize);
  3752. }
  3753. else if (columnType == TypeString)
  3754. {
  3755. columnSize = meta.getColumnRawSize(ii);
  3756. columnSize = rtlQStrLength(columnSize);
  3757. if (columnSize < 1)
  3758. columnSize = STRINGSIZE;
  3759. else if (columnSize > STRINGSIZE)
  3760. columnSize = STRINGSIZE;
  3761. item->setColumnType("String");
  3762. item->setMaxSize(columnSize);
  3763. if (strlen(columnLabel.str()) > columnSize)
  3764. columnSize = strlen(columnLabel.str());
  3765. item->setColumnSize(columnSize);
  3766. }
  3767. else if (columnType == TypeUnicode)
  3768. {
  3769. item->setColumnType("Others");
  3770. columnSize = (int) (meta.getColumnRawSize(ii) * 0.5);
  3771. if (columnSize > STRINGSIZE)
  3772. columnSize = STRINGSIZE;
  3773. item->setColumnSize(columnSize);
  3774. item->setMaxSize(columnSize);
  3775. }
  3776. else
  3777. {
  3778. item->setColumnType("Others");
  3779. columnSize = STRINGSIZE;
  3780. item->setColumnSize(columnSize);
  3781. item->setMaxSize(columnSize);
  3782. }
  3783. }
  3784. columnSize += 7;
  3785. if ((lineSizeCount == 0) && (columnSize > STRINGSIZE))
  3786. {
  3787. if (lineCount >= MAX_KEY_ROWS)
  3788. break;
  3789. dataNonKeyedColumns[lineCount].append(*item.getLink());
  3790. lineCount++;
  3791. }
  3792. else
  3793. {
  3794. if (lineSizeCount + columnSize < STRINGSIZE)
  3795. {
  3796. lineSizeCount += columnSize;
  3797. }
  3798. else
  3799. {
  3800. lineCount++;
  3801. lineSizeCount = columnSize;
  3802. }
  3803. if (lineCount >= MAX_KEY_ROWS)
  3804. break;
  3805. dataNonKeyedColumns[lineCount].append(*item.getLink());
  3806. }
  3807. }
  3808. if (dataKeyedColumns[0].length() > 0)
  3809. resp.setDFUDataKeyedColumns1(dataKeyedColumns[0]);
  3810. if (dataKeyedColumns[1].length() > 0)
  3811. resp.setDFUDataKeyedColumns2(dataKeyedColumns[1]);
  3812. if (dataKeyedColumns[2].length() > 0)
  3813. resp.setDFUDataKeyedColumns3(dataKeyedColumns[2]);
  3814. if (dataKeyedColumns[3].length() > 0)
  3815. resp.setDFUDataKeyedColumns4(dataKeyedColumns[3]);
  3816. if (dataKeyedColumns[4].length() > 0)
  3817. resp.setDFUDataKeyedColumns5(dataKeyedColumns[4]);
  3818. if (dataKeyedColumns[5].length() > 0)
  3819. resp.setDFUDataKeyedColumns6(dataKeyedColumns[5]);
  3820. if (dataKeyedColumns[6].length() > 0)
  3821. resp.setDFUDataKeyedColumns7(dataKeyedColumns[6]);
  3822. if (dataKeyedColumns[7].length() > 0)
  3823. resp.setDFUDataKeyedColumns8(dataKeyedColumns[7]);
  3824. if (dataKeyedColumns[8].length() > 0)
  3825. resp.setDFUDataKeyedColumns9(dataKeyedColumns[8]);
  3826. if (dataKeyedColumns[9].length() > 0)
  3827. resp.setDFUDataKeyedColumns10(dataKeyedColumns[9]);
  3828. if (version > 1.14)
  3829. {
  3830. if (dataKeyedColumns[10].length() > 0)
  3831. resp.setDFUDataKeyedColumns11(dataKeyedColumns[10]);
  3832. if (dataKeyedColumns[11].length() > 0)
  3833. resp.setDFUDataKeyedColumns12(dataKeyedColumns[11]);
  3834. if (dataKeyedColumns[12].length() > 0)
  3835. resp.setDFUDataKeyedColumns13(dataKeyedColumns[12]);
  3836. if (dataKeyedColumns[13].length() > 0)
  3837. resp.setDFUDataKeyedColumns14(dataKeyedColumns[13]);
  3838. if (dataKeyedColumns[14].length() > 0)
  3839. resp.setDFUDataKeyedColumns15(dataKeyedColumns[14]);
  3840. if (dataKeyedColumns[15].length() > 0)
  3841. resp.setDFUDataKeyedColumns16(dataKeyedColumns[15]);
  3842. if (dataKeyedColumns[16].length() > 0)
  3843. resp.setDFUDataKeyedColumns17(dataKeyedColumns[16]);
  3844. if (dataKeyedColumns[17].length() > 0)
  3845. resp.setDFUDataKeyedColumns18(dataKeyedColumns[17]);
  3846. if (dataKeyedColumns[18].length() > 0)
  3847. resp.setDFUDataKeyedColumns19(dataKeyedColumns[18]);
  3848. if (dataKeyedColumns[19].length() > 0)
  3849. resp.setDFUDataKeyedColumns20(dataKeyedColumns[19]);
  3850. }
  3851. if (dataNonKeyedColumns[0].length() > 0)
  3852. resp.setDFUDataNonKeyedColumns1(dataNonKeyedColumns[0]);
  3853. if (dataNonKeyedColumns[1].length() > 0)
  3854. resp.setDFUDataNonKeyedColumns2(dataNonKeyedColumns[1]);
  3855. if (dataNonKeyedColumns[2].length() > 0)
  3856. resp.setDFUDataNonKeyedColumns3(dataNonKeyedColumns[2]);
  3857. if (dataNonKeyedColumns[3].length() > 0)
  3858. resp.setDFUDataNonKeyedColumns4(dataNonKeyedColumns[3]);
  3859. if (dataNonKeyedColumns[4].length() > 0)
  3860. resp.setDFUDataNonKeyedColumns5(dataNonKeyedColumns[4]);
  3861. if (dataNonKeyedColumns[5].length() > 0)
  3862. resp.setDFUDataNonKeyedColumns6(dataNonKeyedColumns[5]);
  3863. if (dataNonKeyedColumns[6].length() > 0)
  3864. resp.setDFUDataNonKeyedColumns7(dataNonKeyedColumns[6]);
  3865. if (dataNonKeyedColumns[7].length() > 0)
  3866. resp.setDFUDataNonKeyedColumns8(dataNonKeyedColumns[7]);
  3867. if (dataNonKeyedColumns[8].length() > 0)
  3868. resp.setDFUDataNonKeyedColumns9(dataNonKeyedColumns[8]);
  3869. if (dataNonKeyedColumns[9].length() > 0)
  3870. resp.setDFUDataNonKeyedColumns10(dataNonKeyedColumns[9]);
  3871. if (version > 1.14)
  3872. {
  3873. if (dataNonKeyedColumns[10].length() > 0)
  3874. resp.setDFUDataNonKeyedColumns11(dataNonKeyedColumns[10]);
  3875. if (dataNonKeyedColumns[11].length() > 0)
  3876. resp.setDFUDataNonKeyedColumns12(dataNonKeyedColumns[11]);
  3877. if (dataNonKeyedColumns[12].length() > 0)
  3878. resp.setDFUDataNonKeyedColumns13(dataNonKeyedColumns[12]);
  3879. if (dataNonKeyedColumns[13].length() > 0)
  3880. resp.setDFUDataNonKeyedColumns14(dataNonKeyedColumns[13]);
  3881. if (dataNonKeyedColumns[14].length() > 0)
  3882. resp.setDFUDataNonKeyedColumns15(dataNonKeyedColumns[14]);
  3883. if (dataNonKeyedColumns[15].length() > 0)
  3884. resp.setDFUDataNonKeyedColumns16(dataNonKeyedColumns[15]);
  3885. if (dataNonKeyedColumns[16].length() > 0)
  3886. resp.setDFUDataNonKeyedColumns17(dataNonKeyedColumns[16]);
  3887. if (dataNonKeyedColumns[17].length() > 0)
  3888. resp.setDFUDataNonKeyedColumns18(dataNonKeyedColumns[17]);
  3889. if (dataNonKeyedColumns[18].length() > 0)
  3890. resp.setDFUDataNonKeyedColumns19(dataNonKeyedColumns[18]);
  3891. if (dataNonKeyedColumns[19].length() > 0)
  3892. resp.setDFUDataNonKeyedColumns20(dataNonKeyedColumns[19]);
  3893. }
  3894. //resp.setColumnCount(columnCount);
  3895. resp.setRowCount(total);
  3896. }
  3897. resp.setLogicalName(logicalNameStr.str());
  3898. resp.setStartIndex(startIndex);
  3899. resp.setEndIndex(endIndex);
  3900. if (version > 1.11)
  3901. {
  3902. if (req.getCluster() && *req.getCluster())
  3903. {
  3904. resp.setCluster(req.getCluster());
  3905. }
  3906. if (req.getClusterType() && *req.getClusterType())
  3907. {
  3908. resp.setClusterType(req.getClusterType());
  3909. }
  3910. }
  3911. }
  3912. if (req.getChooseFile())
  3913. resp.setChooseFile(1);
  3914. else
  3915. resp.setChooseFile(0);
  3916. }
  3917. catch(IException* e)
  3918. {
  3919. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3920. }
  3921. return true;
  3922. }
  3923. bool CWsDfuEx::onDFUSearchData(IEspContext &context, IEspDFUSearchDataRequest &req, IEspDFUSearchDataResponse &resp)
  3924. {
  3925. try
  3926. {
  3927. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  3928. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to View Data File. Permission denied.");
  3929. double version = context.getClientVersion();
  3930. resp.setCluster(req.getCluster());
  3931. resp.setClusterType(req.getClusterType());
  3932. resp.setFile(req.getFile());
  3933. resp.setKey(req.getKey());
  3934. const char* selectedKey = req.getSelectedKey();
  3935. if (strlen(selectedKey) > 0)
  3936. {
  3937. resp.setSelectedKey(req.getSelectedKey());
  3938. }
  3939. else
  3940. {
  3941. resp.setSelectedKey(req.getKey());
  3942. }
  3943. resp.setParentName(req.getParentName());
  3944. resp.setRoxieSelections(req.getRoxieSelections());
  3945. resp.setDisableUppercaseTranslation(req.getDisableUppercaseTranslation());
  3946. const char* openLogicalName = req.getOpenLogicalName();
  3947. if (strlen(openLogicalName) > 0)
  3948. {
  3949. PROGLOG("DFUSearchData: %s", openLogicalName);
  3950. Owned<IEspDFUGetDataColumnsRequest> DataColumnsRequest = createDFUGetDataColumnsRequest();
  3951. Owned<IEspDFUGetDataColumnsResponse> DataColumnsResponse = createDFUGetDataColumnsResponse();
  3952. DataColumnsRequest->setOpenLogicalName(req.getOpenLogicalName());
  3953. DataColumnsRequest->setFilterBy(req.getFilterBy());
  3954. DataColumnsRequest->setShowColumns(req.getShowColumns());
  3955. DataColumnsRequest->setChooseFile(req.getChooseFile());
  3956. DataColumnsRequest->setCluster(req.getCluster());
  3957. DataColumnsRequest->setClusterType(req.getClusterType());
  3958. try
  3959. {
  3960. onDFUGetDataColumns(context, *DataColumnsRequest, *DataColumnsResponse);
  3961. }
  3962. catch(IException* e)
  3963. {
  3964. if (version < 1.08)
  3965. throw e;
  3966. StringBuffer emsg;
  3967. e->errorMessage(emsg);
  3968. e->Release();
  3969. resp.setMsgToDisplay(emsg);
  3970. return true;
  3971. }
  3972. resp.setOpenLogicalName(req.getOpenLogicalName());
  3973. resp.setLogicalName(DataColumnsResponse->getLogicalName());
  3974. resp.setStartIndex(DataColumnsResponse->getStartIndex());
  3975. resp.setEndIndex(DataColumnsResponse->getEndIndex());
  3976. resp.setDFUDataKeyedColumns1(DataColumnsResponse->getDFUDataKeyedColumns1());
  3977. resp.setDFUDataKeyedColumns2(DataColumnsResponse->getDFUDataKeyedColumns2());
  3978. resp.setDFUDataKeyedColumns3(DataColumnsResponse->getDFUDataKeyedColumns3());
  3979. resp.setDFUDataKeyedColumns4(DataColumnsResponse->getDFUDataKeyedColumns4());
  3980. resp.setDFUDataKeyedColumns5(DataColumnsResponse->getDFUDataKeyedColumns5());
  3981. resp.setDFUDataKeyedColumns6(DataColumnsResponse->getDFUDataKeyedColumns6());
  3982. resp.setDFUDataKeyedColumns7(DataColumnsResponse->getDFUDataKeyedColumns7());
  3983. resp.setDFUDataKeyedColumns8(DataColumnsResponse->getDFUDataKeyedColumns8());
  3984. resp.setDFUDataKeyedColumns9(DataColumnsResponse->getDFUDataKeyedColumns9());
  3985. resp.setDFUDataKeyedColumns10(DataColumnsResponse->getDFUDataKeyedColumns10());
  3986. if (version > 1.14)
  3987. {
  3988. resp.setDFUDataKeyedColumns11(DataColumnsResponse->getDFUDataKeyedColumns11());
  3989. resp.setDFUDataKeyedColumns12(DataColumnsResponse->getDFUDataKeyedColumns12());
  3990. resp.setDFUDataKeyedColumns13(DataColumnsResponse->getDFUDataKeyedColumns13());
  3991. resp.setDFUDataKeyedColumns14(DataColumnsResponse->getDFUDataKeyedColumns14());
  3992. resp.setDFUDataKeyedColumns15(DataColumnsResponse->getDFUDataKeyedColumns15());
  3993. resp.setDFUDataKeyedColumns16(DataColumnsResponse->getDFUDataKeyedColumns16());
  3994. resp.setDFUDataKeyedColumns17(DataColumnsResponse->getDFUDataKeyedColumns17());
  3995. resp.setDFUDataKeyedColumns18(DataColumnsResponse->getDFUDataKeyedColumns18());
  3996. resp.setDFUDataKeyedColumns19(DataColumnsResponse->getDFUDataKeyedColumns19());
  3997. resp.setDFUDataKeyedColumns20(DataColumnsResponse->getDFUDataKeyedColumns20());
  3998. }
  3999. resp.setDFUDataNonKeyedColumns1(DataColumnsResponse->getDFUDataNonKeyedColumns1());
  4000. resp.setDFUDataNonKeyedColumns2(DataColumnsResponse->getDFUDataNonKeyedColumns2());
  4001. resp.setDFUDataNonKeyedColumns3(DataColumnsResponse->getDFUDataNonKeyedColumns3());
  4002. resp.setDFUDataNonKeyedColumns4(DataColumnsResponse->getDFUDataNonKeyedColumns4());
  4003. resp.setDFUDataNonKeyedColumns5(DataColumnsResponse->getDFUDataNonKeyedColumns5());
  4004. resp.setDFUDataNonKeyedColumns6(DataColumnsResponse->getDFUDataNonKeyedColumns6());
  4005. resp.setDFUDataNonKeyedColumns7(DataColumnsResponse->getDFUDataNonKeyedColumns7());
  4006. resp.setDFUDataNonKeyedColumns8(DataColumnsResponse->getDFUDataNonKeyedColumns8());
  4007. resp.setDFUDataNonKeyedColumns9(DataColumnsResponse->getDFUDataNonKeyedColumns9());
  4008. resp.setDFUDataNonKeyedColumns10(DataColumnsResponse->getDFUDataNonKeyedColumns10());
  4009. if (version > 1.14)
  4010. {
  4011. resp.setDFUDataNonKeyedColumns11(DataColumnsResponse->getDFUDataNonKeyedColumns11());
  4012. resp.setDFUDataNonKeyedColumns12(DataColumnsResponse->getDFUDataNonKeyedColumns12());
  4013. resp.setDFUDataNonKeyedColumns13(DataColumnsResponse->getDFUDataNonKeyedColumns13());
  4014. resp.setDFUDataNonKeyedColumns14(DataColumnsResponse->getDFUDataNonKeyedColumns14());
  4015. resp.setDFUDataNonKeyedColumns15(DataColumnsResponse->getDFUDataNonKeyedColumns15());
  4016. resp.setDFUDataNonKeyedColumns16(DataColumnsResponse->getDFUDataNonKeyedColumns16());
  4017. resp.setDFUDataNonKeyedColumns17(DataColumnsResponse->getDFUDataNonKeyedColumns17());
  4018. resp.setDFUDataNonKeyedColumns18(DataColumnsResponse->getDFUDataNonKeyedColumns18());
  4019. resp.setDFUDataNonKeyedColumns19(DataColumnsResponse->getDFUDataNonKeyedColumns19());
  4020. resp.setDFUDataNonKeyedColumns20(DataColumnsResponse->getDFUDataNonKeyedColumns20());
  4021. }
  4022. resp.setRowCount(DataColumnsResponse->getRowCount());
  4023. resp.setShowColumns(DataColumnsResponse->getShowColumns());
  4024. resp.setChooseFile(DataColumnsResponse->getChooseFile());
  4025. }
  4026. const char* logicalName = req.getLogicalName();
  4027. if (strlen(logicalName) == 0 && strlen(openLogicalName) > 0)
  4028. {
  4029. logicalName = openLogicalName;
  4030. }
  4031. if (strlen(logicalName) > 0)
  4032. {
  4033. Owned<IEspDFUBrowseDataRequest> browseDataRequest = createDFUBrowseDataRequest();
  4034. Owned<IEspDFUBrowseDataResponse> browseDataResponse = createDFUBrowseDataResponse();
  4035. browseDataRequest->setLogicalName(logicalName);
  4036. const char* parentName = req.getParentName();
  4037. if (parentName && *parentName)
  4038. browseDataRequest->setParentName(parentName);
  4039. browseDataRequest->setFilterBy(req.getFilterBy());
  4040. browseDataRequest->setShowColumns(req.getShowColumns());
  4041. browseDataRequest->setStartForGoback(req.getStartForGoback());
  4042. browseDataRequest->setCountForGoback(req.getCountForGoback());
  4043. browseDataRequest->setChooseFile(req.getChooseFile());
  4044. browseDataRequest->setStart(req.getStart());
  4045. browseDataRequest->setCount(req.getCount());
  4046. browseDataRequest->setSchemaOnly(req.getSchemaOnly());
  4047. browseDataRequest->setCluster(req.getCluster());
  4048. browseDataRequest->setClusterType(req.getClusterType());
  4049. browseDataRequest->setDisableUppercaseTranslation(req.getDisableUppercaseTranslation());
  4050. onDFUBrowseData(context, *browseDataRequest, *browseDataResponse);
  4051. resp.setName(browseDataResponse->getName());
  4052. resp.setLogicalName(browseDataResponse->getLogicalName());
  4053. resp.setFilterBy(browseDataResponse->getFilterBy());
  4054. resp.setFilterForGoBack(browseDataResponse->getFilterForGoBack());
  4055. resp.setColumnsHidden(browseDataResponse->getColumnsHidden());
  4056. resp.setColumnsHidden(browseDataResponse->getColumnsHidden());
  4057. resp.setColumnCount(browseDataResponse->getColumnCount());
  4058. resp.setStartForGoback(browseDataResponse->getStartForGoback());
  4059. resp.setCountForGoback(browseDataResponse->getCountForGoback());
  4060. resp.setChooseFile(browseDataResponse->getChooseFile());
  4061. resp.setStart(browseDataResponse->getStart());
  4062. resp.setCount(browseDataResponse->getCount());
  4063. resp.setPageSize(browseDataResponse->getPageSize());
  4064. resp.setTotal(browseDataResponse->getTotal());
  4065. resp.setResult(browseDataResponse->getResult());
  4066. resp.setMsgToDisplay(browseDataResponse->getMsgToDisplay());
  4067. resp.setSchemaOnly(browseDataResponse->getSchemaOnly());
  4068. resp.setAutoUppercaseTranslation(!m_disableUppercaseTranslation);
  4069. }
  4070. }
  4071. catch(IException* e)
  4072. {
  4073. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4074. }
  4075. return true;
  4076. }
  4077. static const char * const columnTypes[] = { "Boolean", "Integer", "Unsigned Integer", "Real", "String",
  4078. "Data", "Unicode", "Unknown", "BeginIfBlock", "EndIfBlock", "BeginRecord", "EndRecord", "Set", "Dataset", NULL };
  4079. bool CWsDfuEx::onDFUGetFileMetaData(IEspContext &context, IEspDFUGetFileMetaDataRequest & req, IEspDFUGetFileMetaDataResponse & resp)
  4080. {
  4081. class CDFUFileMetaDataReader
  4082. {
  4083. unsigned totalColumnCount;
  4084. unsigned keyedColumnCount;
  4085. StringBuffer XmlSchema, XmlXPathSchema;
  4086. IArrayOf<IEspDFUDataColumn> dataColumns;
  4087. const IResultSetMetaData& metaRoot;
  4088. bool readRootLevelColumns;
  4089. IEspContext &context;
  4090. bool readColumnLabel(const IResultSetMetaData* meta, unsigned columnID, IEspDFUDataColumn* out)
  4091. {
  4092. SCMStringBuffer columnLabel;
  4093. bool isNaturalColumn = true;
  4094. if (meta->hasSetTranslation(columnID))
  4095. meta->getNaturalColumnLabel(columnLabel, columnID);
  4096. if (columnLabel.length() < 1)
  4097. {
  4098. meta->getColumnLabel(columnLabel, columnID);
  4099. isNaturalColumn = false;
  4100. }
  4101. out->setColumnLabel(columnLabel.str());
  4102. out->setIsNaturalColumn(isNaturalColumn);
  4103. return isNaturalColumn;
  4104. }
  4105. void readColumn(const IResultSetMetaData* meta, unsigned& columnID, const bool isKeyed,
  4106. IArrayOf<IEspDFUDataColumn>& dataColumns)
  4107. {
  4108. double version = context.getClientVersion();
  4109. Owned<IEspDFUDataColumn> dataItem = createDFUDataColumn();
  4110. dataItem->setColumnID(columnID+1);
  4111. dataItem->setIsKeyedColumn(isKeyed);
  4112. SCMStringBuffer s;
  4113. dataItem->setColumnEclType(meta->getColumnEclType(s, columnID).str());
  4114. DisplayType columnType = meta->getColumnDisplayType(columnID);
  4115. if ((columnType == TypeUnicode) || columnType == TypeString)
  4116. dataItem->setColumnRawSize(meta->getColumnRawSize(columnID));
  4117. if (readColumnLabel(meta, columnID, dataItem))
  4118. dataItem->setColumnType("Others");
  4119. else if (columnType == TypeBeginRecord)
  4120. dataItem->setColumnType("Record");
  4121. else
  4122. dataItem->setColumnType(columnTypes[columnType]);
  4123. if ((version >= 1.31) && ((columnType == TypeSet) || (columnType == TypeDataset) || (columnType == TypeBeginRecord)))
  4124. checkAndReadNestedColumn(meta, columnID, columnType, dataItem);
  4125. dataColumns.append(*dataItem.getClear());
  4126. }
  4127. void readColumns(const IResultSetMetaData* meta, IArrayOf<IEspDFUDataColumn>& dataColumnArray)
  4128. {
  4129. if (!meta)
  4130. return;
  4131. if (readRootLevelColumns)
  4132. {
  4133. readRootLevelColumns = false;
  4134. totalColumnCount = (unsigned)meta->getColumnCount();
  4135. keyedColumnCount = meta->getNumKeyedColumns();
  4136. unsigned i = 0;
  4137. for (; i < keyedColumnCount; i++)
  4138. readColumn(meta, i, true, dataColumnArray);
  4139. for (i = keyedColumnCount; i < totalColumnCount; i++)
  4140. readColumn(meta, i, false, dataColumnArray);
  4141. }
  4142. else
  4143. {
  4144. unsigned columnCount = (unsigned)meta->getColumnCount();
  4145. for (unsigned i = 0; i < columnCount; i++)
  4146. readColumn(meta, i, false, dataColumnArray);
  4147. }
  4148. }
  4149. void checkAndReadNestedColumn(const IResultSetMetaData* meta, unsigned& columnID,
  4150. DisplayType columnType, IEspDFUDataColumn* dataItem)
  4151. {
  4152. IArrayOf<IEspDFUDataColumn> curDataColumnArray;
  4153. if (columnType == TypeBeginRecord)
  4154. {
  4155. columnID++;
  4156. do
  4157. {
  4158. readColumn(meta, columnID, false, curDataColumnArray);
  4159. } while (meta->getColumnDisplayType(++columnID) != TypeEndRecord);
  4160. }
  4161. else
  4162. readColumns(meta->getChildMeta(columnID), curDataColumnArray);
  4163. dataItem->setDataColumns(curDataColumnArray);
  4164. }
  4165. public:
  4166. CDFUFileMetaDataReader(IEspContext& _context, const IResultSetMetaData& _meta)
  4167. : context(_context), metaRoot(_meta), readRootLevelColumns(true)
  4168. {
  4169. readColumns(&metaRoot, dataColumns);
  4170. };
  4171. inline unsigned getTotalColumnCount() { return totalColumnCount; }
  4172. inline unsigned getKeyedColumnCount() { return keyedColumnCount; }
  4173. inline IArrayOf<IEspDFUDataColumn>& getDataColumns() { return dataColumns; }
  4174. inline StringBuffer& getXmlSchema(StringBuffer& s, const bool addHeader)
  4175. {
  4176. StringBufferAdaptor schema(s);
  4177. metaRoot.getXmlSchema(schema, addHeader);
  4178. return s;
  4179. }
  4180. inline StringBuffer& getXmlXPathSchema(StringBuffer& s, const bool addHeader)
  4181. {
  4182. StringBufferAdaptor XPathSchema(s);
  4183. metaRoot.getXmlXPathSchema(XPathSchema, addHeader);
  4184. return s;
  4185. }
  4186. };
  4187. try
  4188. {
  4189. StringBuffer fileNameStr = req.getLogicalFileName();
  4190. const char* fileName = fileNameStr.trim().str();
  4191. if (!fileName || !*fileName)
  4192. throw MakeStringException(ECLWATCH_INVALID_INPUT, "CWsDfuEx::onDFUGetFileMetaData: LogicalFileName not set");
  4193. const char* cluster = NULL;
  4194. StringBuffer clusterNameStr = req.getClusterName();
  4195. if (clusterNameStr.trim().length() > 0)
  4196. cluster = clusterNameStr.str();
  4197. PROGLOG("DFUGetFileMetaData: %s", fileName);
  4198. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  4199. Owned<INewResultSet> result = resultSetFactory->createNewFileResultSet(fileName, cluster);
  4200. if (!result)
  4201. throw MakeStringException(ECLWATCH_INVALID_INPUT, "CWsDfuEx::onDFUGetFileMetaData: Failed to access FileResultSet for %s.", fileName);
  4202. CDFUFileMetaDataReader dataReader(context, result->getMetaData());
  4203. resp.setTotalColumnCount(dataReader.getTotalColumnCount());
  4204. resp.setKeyedColumnCount(dataReader.getKeyedColumnCount());
  4205. resp.setDataColumns(dataReader.getDataColumns());
  4206. StringBuffer s, s1;
  4207. if (req.getIncludeXmlSchema())
  4208. resp.setXmlSchema(dataReader.getXmlSchema(s, req.getAddHeaderInXmlSchema()).str());
  4209. if (req.getIncludeXmlXPathSchema())
  4210. resp.setXmlXPathSchema(dataReader.getXmlXPathSchema(s1, req.getAddHeaderInXmlXPathSchema()).str());
  4211. resp.setTotalResultRows(result->getNumRows());
  4212. }
  4213. catch(IException* e)
  4214. {
  4215. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4216. }
  4217. return true;
  4218. }
  4219. bool CWsDfuEx::onDFUBrowseData(IEspContext &context, IEspDFUBrowseDataRequest &req, IEspDFUBrowseDataResponse &resp)
  4220. {
  4221. try
  4222. {
  4223. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Read, false))
  4224. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to View Data File. Permission denied.");
  4225. const char* logicalName0 = req.getLogicalName();
  4226. const char* parentName = req.getParentName();
  4227. if (!logicalName0 || !*logicalName0)
  4228. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No LogicalName defined.");
  4229. StringBuffer logicalNameStr;
  4230. if (logicalName0 && *logicalName0)
  4231. {
  4232. logicalNameStr.append(logicalName0);
  4233. logicalNameStr.trim();
  4234. if (logicalNameStr.length() < 1)
  4235. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No LogicalName defined.");
  4236. }
  4237. PROGLOG("DFUBrowseData: %s", logicalNameStr.str());
  4238. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  4239. __int64 count=req.getCount() ? req.getCount() : 20, requested=count;
  4240. if (count > MAX_VIEWKEYFILE_ROWS)
  4241. throw MakeStringException(ECLWATCH_TOO_MANY_DATA_ROWS,"Browser Cannot display more than %d data rows.", MAX_VIEWKEYFILE_ROWS);
  4242. bool bSchemaOnly=req.getSchemaOnly() ? req.getSchemaOnly() : false;
  4243. bool bDisableUppercaseTranslation = req.getDisableUppercaseTranslation() ? req.getDisableUppercaseTranslation() : false;
  4244. const char* filterBy = req.getFilterBy();
  4245. const char* showColumns = req.getShowColumns();
  4246. __int64 read=0;
  4247. __int64 total = 0;
  4248. StringBuffer msg;
  4249. StringArray columnLabels, columnLabelsType;
  4250. IArrayOf<IEspDFUData> DataList;
  4251. int iRet = GetIndexData(context, bSchemaOnly, logicalNameStr.str(), parentName, filterBy, start, count, read, total, msg, columnLabels, columnLabelsType, DataList, bDisableUppercaseTranslation);
  4252. if (iRet > 0)
  4253. resp.setMsgToDisplay("This search has timed out due to the restrictive filter. There may be more records.");
  4254. //GetIndexData(context, bSchemaOnly, logicalNameStr.str(), "roxie::thor_data400::key::bankruptcyv2::20090721::search::tmsid", filterBy, start, count, read, total, msg, columnLabels, columnLabelsType, DataList);
  4255. resp.setResult(DataList.item(0).getData());
  4256. unsigned int max_name_length = 3; //max length for name length
  4257. unsigned int max_value_length = 4; //max length for value length:
  4258. StringBuffer filterByStr, filterByStr0;
  4259. filterByStr0.appendf("%d%d", max_name_length, max_value_length);
  4260. unsigned columnCount = columnLabels.length();
  4261. IArrayOf<IEspDFUDataColumn> dataColumns;
  4262. double version = context.getClientVersion();
  4263. if (version > 1.04 && columnCount > 0)
  4264. {
  4265. //Find out which columns need to be displayed
  4266. int lenShowCols = 0, showCols[1024];
  4267. const char* showColumns = req.getShowColumns();
  4268. char *pShowColumns = (char*) showColumns;
  4269. while (pShowColumns && *pShowColumns)
  4270. {
  4271. StringBuffer buf;
  4272. while (pShowColumns && isdigit(pShowColumns[0]))
  4273. {
  4274. buf.append(pShowColumns[0]);
  4275. pShowColumns++;
  4276. }
  4277. if (buf.length() > 0)
  4278. {
  4279. showCols[lenShowCols] = atoi(buf.str());
  4280. lenShowCols++;
  4281. }
  4282. if (!pShowColumns || !*pShowColumns)
  4283. break;
  4284. pShowColumns++;
  4285. }
  4286. for(unsigned col = 0; col < columnCount; col++)
  4287. {
  4288. const char* label = columnLabels.item(col);
  4289. const char* type = columnLabelsType.item(col);
  4290. if (!label || !*label || !type || !*type)
  4291. continue;
  4292. Owned<IEspDFUDataColumn> item = createDFUDataColumn("","");
  4293. item->setColumnLabel(label);
  4294. item->setColumnType(type);
  4295. item->setColumnSize(0); //not show this column
  4296. if (!showColumns || !*showColumns)
  4297. {
  4298. item->setColumnSize(1); //Show this column
  4299. }
  4300. else
  4301. {
  4302. for(int col1 = 0; col1 < lenShowCols; col1++)
  4303. {
  4304. if (col == showCols[col1])
  4305. {
  4306. item->setColumnSize(1); //Show this column
  4307. break;
  4308. }
  4309. }
  4310. }
  4311. dataColumns.append(*item.getLink());
  4312. }
  4313. //Re-build filters
  4314. if (filterBy && *filterBy)
  4315. {
  4316. StringArray filterByNames, filterByValues;
  4317. parseTwoStringArrays(filterBy, filterByNames, filterByValues);
  4318. if (filterByNames.length() > 0)
  4319. {
  4320. for (unsigned ii = 0; ii < filterByNames.length(); ii++)
  4321. {
  4322. const char* columnName = filterByNames.item(ii);
  4323. const char* columnValue = filterByValues.item(ii);
  4324. if (columnName && *columnName && columnValue && *columnValue)
  4325. {
  4326. filterByStr.appendf("%s[%s]", columnName, columnValue);
  4327. filterByStr0.appendf("%03d%04d%s%s", (int) strlen(columnName), (int) strlen(columnValue), columnName, columnValue);
  4328. }
  4329. }
  4330. }
  4331. }
  4332. if (req.getStartForGoback())
  4333. resp.setStartForGoback(req.getStartForGoback());
  4334. if (req.getCountForGoback())
  4335. resp.setCountForGoback(req.getCountForGoback());
  4336. }
  4337. //resp.setFilterBy(filterByStr.str());
  4338. if (filterByStr.length() > 0)
  4339. {
  4340. const char* oldStr = "&";
  4341. const char* newStr = "&amp;";
  4342. filterByStr.replaceString(oldStr, newStr);
  4343. resp.setFilterBy(filterByStr.str());
  4344. }
  4345. if (version > 1.04)
  4346. {
  4347. //resp.setFilterForGoBack(filterByStr0.str());
  4348. if (filterByStr0.length() > 0)
  4349. {
  4350. const char* oldStr = "&";
  4351. const char* newStr = "&amp;";
  4352. filterByStr0.replaceString(oldStr, newStr);
  4353. resp.setFilterForGoBack(filterByStr0.str());
  4354. }
  4355. resp.setColumnCount(columnCount);
  4356. if (dataColumns.length() > 0)
  4357. resp.setColumnsHidden(dataColumns);
  4358. }
  4359. if (version > 1.10)
  4360. {
  4361. resp.setSchemaOnly(bSchemaOnly);
  4362. }
  4363. //resp.setName(name.str());
  4364. resp.setLogicalName(logicalNameStr.str());
  4365. resp.setStart(start);
  4366. //if (requested > read)
  4367. // requested = read;
  4368. resp.setPageSize(requested);
  4369. if (count > read)
  4370. {
  4371. count = read;
  4372. }
  4373. resp.setCount(count);
  4374. if (total != UNKNOWN_NUM_ROWS)
  4375. resp.setTotal(total);
  4376. else
  4377. resp.setTotal(-1);
  4378. if (req.getChooseFile())
  4379. resp.setChooseFile(1);
  4380. else
  4381. resp.setChooseFile(0);
  4382. if (version > 1.11)
  4383. {
  4384. if (req.getCluster() && *req.getCluster())
  4385. {
  4386. resp.setCluster(req.getCluster());
  4387. }
  4388. if (req.getClusterType() && *req.getClusterType())
  4389. {
  4390. resp.setClusterType(req.getClusterType());
  4391. }
  4392. }
  4393. if ((version > 1.12) && parentName && *parentName)
  4394. {
  4395. resp.setParentName(parentName);
  4396. }
  4397. }
  4398. catch(IException* e)
  4399. {
  4400. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4401. }
  4402. return true;
  4403. }
  4404. void storeHistoryTreeToArray(IPropertyTree *history, IArrayOf<IEspHistory>& arrHistory)
  4405. {
  4406. Owned<IPropertyTreeIterator> historyIter = history->getElements("*");
  4407. ForEach(*historyIter)
  4408. {
  4409. Owned<IEspHistory> historyRecord = createHistory();
  4410. IPropertyTree & item = historyIter->query();
  4411. historyRecord->setIP(item.queryProp("@ip"));
  4412. historyRecord->setName(item.queryProp("@name"));
  4413. historyRecord->setOperation(item.queryProp("@operation"));
  4414. historyRecord->setOwner(item.queryProp("@owner"));
  4415. historyRecord->setPath(item.queryProp("@path"));
  4416. historyRecord->setTimestamp(item.queryProp("@timestamp"));
  4417. historyRecord->setWorkunit(item.queryProp("@workunit"));
  4418. arrHistory.append(*historyRecord.getClear());
  4419. }
  4420. }
  4421. bool CWsDfuEx::onListHistory(IEspContext &context, IEspListHistoryRequest &req, IEspListHistoryResponse &resp)
  4422. {
  4423. try
  4424. {
  4425. StringBuffer username;
  4426. context.getUserID(username);
  4427. Owned<IUserDescriptor> userdesc;
  4428. if (username.length() > 0)
  4429. {
  4430. userdesc.setown(createUserDescriptor());
  4431. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  4432. }
  4433. if (!req.getName() || !*req.getName())
  4434. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Name required");
  4435. PROGLOG("onListHistory: %s", req.getName());
  4436. MemoryBuffer xmlmap;
  4437. IArrayOf<IEspHistory> arrHistory;
  4438. Owned<IDistributedFile> file = queryDistributedFileDirectory().lookup(req.getName(),userdesc.get());
  4439. if (file)
  4440. {
  4441. IPropertyTree *history = file->queryHistory();
  4442. if (history)
  4443. {
  4444. storeHistoryTreeToArray(history, arrHistory);
  4445. if (context.getClientVersion() < 1.36)
  4446. history->serialize(xmlmap);
  4447. }
  4448. if (arrHistory.ordinality())
  4449. resp.setHistory(arrHistory);
  4450. }
  4451. else
  4452. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"CWsDfuEx::onListHistory: Could not find file '%s'.", req.getName());
  4453. if (xmlmap.length())
  4454. resp.setXmlmap(xmlmap);
  4455. }
  4456. catch(IException* e)
  4457. {
  4458. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4459. }
  4460. return true;
  4461. }
  4462. bool CWsDfuEx::onEraseHistory(IEspContext &context, IEspEraseHistoryRequest &req, IEspEraseHistoryResponse &resp)
  4463. {
  4464. try
  4465. {
  4466. if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Full, false))
  4467. throw MakeStringException(ECLWATCH_DFU_ACCESS_DENIED, "Failed to Erase History. Permission denied (requires Full).");
  4468. StringBuffer username;
  4469. context.getUserID(username);
  4470. Owned<IUserDescriptor> userdesc;
  4471. if (username.length() > 0)
  4472. {
  4473. userdesc.setown(createUserDescriptor());
  4474. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  4475. }
  4476. if (!req.getName() || !*req.getName())
  4477. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Name required");
  4478. PROGLOG("onEraseHistory: %s", req.getName());
  4479. MemoryBuffer xmlmap;
  4480. IArrayOf<IEspHistory> arrHistory;
  4481. Owned<IDistributedFile> file = queryDistributedFileDirectory().lookup(req.getName(),userdesc.get());
  4482. if (file)
  4483. {
  4484. IPropertyTree *history = file->queryHistory();
  4485. if (history)
  4486. {
  4487. storeHistoryTreeToArray(history, arrHistory);
  4488. if (context.getClientVersion() < 1.36)
  4489. history->serialize(xmlmap);
  4490. file->resetHistory();
  4491. }
  4492. if (arrHistory.ordinality())
  4493. resp.setHistory(arrHistory);
  4494. }
  4495. else
  4496. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"CWsDfuEx::onEraseHistory: Could not find file '%s'.", req.getName());
  4497. if (xmlmap.length())
  4498. resp.setXmlmap(xmlmap);
  4499. }
  4500. catch(IException* e)
  4501. {
  4502. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4503. }
  4504. return true;
  4505. }
  4506. //////////////////////HPCC Browser//////////////////////////
  4507. static const char* SCHEMANAME = "myschema";
  4508. //void CWsDfuEx::setRootFilter(INewResultSet* result, const char* filterBy, IFilteredResultSet* filter)
  4509. void CWsDfuEx::setRootFilter(INewResultSet* result, const char* filterBy, IResultSetFilter* filter, bool disableUppercaseTranslation)
  4510. {
  4511. if (!filterBy || !*filterBy || !result)
  4512. return;
  4513. //Owned<IFilteredResultSet> filter = result->createFiltered();
  4514. filter->clearFilters();
  4515. const IResultSetMetaData &meta = result->getMetaData();
  4516. unsigned columnCount = meta.getColumnCount();
  4517. if (columnCount < 1)
  4518. return;
  4519. StringArray filterByNames, filterByValues;
  4520. parseTwoStringArrays(filterBy, filterByNames, filterByValues);
  4521. if (filterByNames.length() < 1)
  4522. return;
  4523. for (unsigned ii = 0; ii < filterByNames.length(); ii++)
  4524. {
  4525. const char* columnName = filterByNames.item(ii);
  4526. const char* columnValue0 = filterByValues.item(ii);
  4527. if (!columnName || !*columnName || !columnValue0 || !*columnValue0)
  4528. continue;
  4529. StringBuffer buf(columnValue0);
  4530. if (!disableUppercaseTranslation)
  4531. buf.toUpperCase();
  4532. const char* columnValue = buf.str();
  4533. for(unsigned col = 0; col < columnCount; col++)
  4534. {
  4535. bool hasSetTranslation = false;
  4536. SCMStringBuffer scmbuf;
  4537. if (meta.hasSetTranslation(col))
  4538. {
  4539. hasSetTranslation = true;
  4540. meta.getNaturalColumnLabel(scmbuf, col);
  4541. }
  4542. if (scmbuf.length() < 1)
  4543. {
  4544. meta.getColumnLabel(scmbuf, col);
  4545. }
  4546. if (!stricmp(scmbuf.str(), columnName))
  4547. {
  4548. //filter->addFilter(col, columnValue);
  4549. //filterByStr.appendf("%s[%s]", columnName, columnValue);
  4550. //filterByStr0.appendf("%03d%04d%s%s", strlen(columnName), strlen(columnValue), columnName, columnValue);
  4551. if (hasSetTranslation)
  4552. filter->addNaturalFilter(col, strlen(columnValue), columnValue);
  4553. else
  4554. filter->addFilter(col, strlen(columnValue), columnValue);
  4555. break;
  4556. }
  4557. }
  4558. }
  4559. //result.setown(filter->create());
  4560. return;
  4561. }
  4562. void CWsDfuEx::getMappingColumns(IRelatedBrowseFile * file, bool isPrimary, UnsignedArray& cols)
  4563. {
  4564. const char* logicalName = file->queryDefinition()->queryDistributedFile()->queryLogicalName();
  4565. const char* primaryName = file->queryParentRelation()->queryFileRelationship()->queryPrimaryFilename();
  4566. if (!logicalName || !primaryName || strcmp(logicalName, primaryName))
  4567. return;
  4568. IViewRelation* parentRelation = file->queryParentRelation();
  4569. for (unsigned i=0; i < parentRelation->numMappingFields(); i++)
  4570. {
  4571. //find out the column numbers to remove
  4572. unsigned col = parentRelation->queryMappingField(i, isPrimary);
  4573. cols.append(col);
  4574. }
  4575. #ifdef TESTDATASET
  4576. cols.kill();
  4577. cols.append(2);
  4578. cols.append(3);
  4579. #endif
  4580. return;
  4581. }
  4582. void CWsDfuEx::readColumnsForDisplay(StringBuffer& schemaText, StringArray& columnsDisplay, StringArray& columnsDisplayType)
  4583. {
  4584. if (schemaText.length() < 1)
  4585. return;
  4586. Owned<IPropertyTree> schema = createPTreeFromXMLString(schemaText.str());
  4587. if (!schema)
  4588. return;
  4589. //Find out labels from the second schema used for column mapping
  4590. columnsDisplay.kill();
  4591. Owned<IPropertyTreeIterator> rows4 = schema->getElements("xs:element[@name=\"Dataset\"]/xs:complexType/xs:sequence/xs:element[@name=\"Row\"]/xs:complexType/xs:sequence/*");
  4592. ForEach(*rows4)
  4593. {
  4594. IPropertyTree &e = rows4->query();
  4595. const char* name = e.queryProp("@name");
  4596. const char* type = e.queryProp("@type");
  4597. bool hasChildren = e.hasChildren();
  4598. if (!name || !*name)
  4599. continue;
  4600. columnsDisplay.append(name); //Display this column
  4601. if (type && *type)
  4602. columnsDisplayType.append(type);
  4603. else if (hasChildren)
  4604. columnsDisplayType.append("Object");
  4605. else
  4606. columnsDisplayType.append("Unknown");
  4607. }
  4608. return;
  4609. }
  4610. void CWsDfuEx::mergeSchema(IRelatedBrowseFile * file, StringBuffer& schemaText, StringBuffer schemaText2,
  4611. StringArray& columnsDisplay, StringArray& columnsDisplayType, StringArray& columnsHide)
  4612. {
  4613. if (schemaText.length() < 1)
  4614. return;
  4615. if (schemaText2.length() < 1)
  4616. return;
  4617. Owned<IPropertyTree> schema = createPTreeFromXMLString(schemaText.str());
  4618. Owned<IPropertyTree> schema2 = createPTreeFromXMLString(schemaText2.str());
  4619. if (!schema || !schema2)
  4620. return;
  4621. //Process simpleType part
  4622. Owned<IPropertyTreeIterator> rows1 = schema->getElements("xs:simpleType");
  4623. Owned<IPropertyTreeIterator> rows2 = schema2->getElements("xs:simpleType");
  4624. if (!rows1 || !rows2)
  4625. return;
  4626. ForEach(*rows2)
  4627. {
  4628. IPropertyTree &e = rows2->query();
  4629. const char* name = e.queryProp("@name");
  4630. if (!name || !*name)
  4631. continue;
  4632. bool bFound = false;
  4633. ForEach(*rows1)
  4634. {
  4635. IPropertyTree &e1 = rows1->query();
  4636. const char* name1 = e1.queryProp("@name");
  4637. if (!name1 || !*name1 || stricmp(name1, name))
  4638. continue;
  4639. bFound = true;
  4640. break;
  4641. }
  4642. if (!bFound)
  4643. schema->addPropTree(e.queryName(), LINK(&e));
  4644. }
  4645. IPropertyTree* rows = schema->queryBranch("xs:element[@name=\"Dataset\"]/xs:complexType/xs:sequence/xs:element[@name=\"Row\"]/xs:complexType/xs:sequence");
  4646. if (!rows)
  4647. return;
  4648. //Find out labels used for column mapping
  4649. columnsDisplay.kill();
  4650. columnsDisplayType.kill();
  4651. columnsHide.kill();
  4652. Owned<IPropertyTreeIterator> rows4 = schema->getElements("xs:element[@name=\"Dataset\"]/xs:complexType/xs:sequence/xs:element[@name=\"Row\"]/xs:complexType/xs:sequence/*");
  4653. ForEach(*rows4)
  4654. {
  4655. IPropertyTree &e = rows4->query();
  4656. const char* name = e.queryProp("@name");
  4657. const char* type = e.queryProp("@type");
  4658. bool hasChildren = e.hasChildren();
  4659. if (!name || !*name)
  4660. continue;
  4661. columnsDisplay.append(name); //Display this column
  4662. if (type && *type)
  4663. columnsDisplayType.append(type);
  4664. else if (hasChildren)
  4665. columnsDisplayType.append("Object");
  4666. else
  4667. columnsDisplayType.append("Unknown");
  4668. }
  4669. UnsignedArray cols;
  4670. bool isPrimary = true;
  4671. getMappingColumns(file, isPrimary, cols);
  4672. //Process complexType part for labels
  4673. unsigned col0 = 0;
  4674. Owned<IPropertyTreeIterator> rows3 = schema2->getElements("xs:element[@name=\"Dataset\"]/xs:complexType/xs:sequence/xs:element[@name=\"Row\"]/xs:complexType/xs:sequence/*");
  4675. ForEach(*rows3)
  4676. {
  4677. IPropertyTree &e = rows3->query();
  4678. const char* name = e.queryProp("@name");
  4679. const char* type = e.queryProp("@type");
  4680. bool hasChildren = e.hasChildren();
  4681. if (!name || !*name)
  4682. continue;
  4683. bool bAdd = true;
  4684. bool bRename = false;
  4685. if (cols.ordinality() != 0)
  4686. {
  4687. ForEachItemIn(i1,cols)
  4688. {
  4689. unsigned col = cols.item(i1);
  4690. if (col == col0)
  4691. {
  4692. bAdd = false;
  4693. break;
  4694. }
  4695. }
  4696. }
  4697. #define RENAMESAMECOLUMN
  4698. #ifdef RENAMESAMECOLUMN
  4699. if (columnsDisplay.length() > 0)
  4700. {
  4701. for (unsigned i = 0; i < columnsDisplay.length(); i++)
  4702. {
  4703. const char* label = columnsDisplay.item(i);
  4704. if (!label || strcmp(label, name))
  4705. continue;
  4706. bRename = true;
  4707. break;
  4708. }
  4709. }
  4710. #endif
  4711. if (!bAdd)
  4712. {
  4713. columnsHide.append(name); //hide this column
  4714. }
  4715. else
  4716. {
  4717. if (type && *type)
  4718. columnsDisplayType.append(type);
  4719. else if (hasChildren)
  4720. columnsDisplayType.append("Object");
  4721. else
  4722. columnsDisplayType.append("Unknown");
  4723. #ifdef RENAMESAMECOLUMN
  4724. if (bRename)
  4725. {
  4726. StringBuffer newName(name);
  4727. newName.append("-2");
  4728. columnsDisplay.append(newName.str()); //Display this column
  4729. e.setProp("@name", newName.str());
  4730. rows->addPropTree(e.queryName(), LINK(&e));
  4731. }
  4732. else
  4733. {
  4734. #endif
  4735. columnsDisplay.append(name); //Display this column
  4736. rows->addPropTree(e.queryName(), LINK(&e));
  4737. #ifdef RENAMESAMECOLUMN
  4738. }
  4739. #endif
  4740. }
  4741. col0++;
  4742. }
  4743. //Convert schema tree to schame now
  4744. schemaText.clear();
  4745. toXML(schema, schemaText);
  4746. return;
  4747. }
  4748. void CWsDfuEx::mergeDataRow(StringBuffer& newRow, int depth, IPropertyTreeIterator* it, StringArray& columnsHide, StringArray& columnsUsed)
  4749. {
  4750. if (!it)
  4751. return;
  4752. it->first();
  4753. while(it->isValid())
  4754. {
  4755. IPropertyTree* e = &it->query();
  4756. if (e)
  4757. {
  4758. const char* label = e->queryName();
  4759. if (label && *label)
  4760. {
  4761. #ifdef RENAMESAMECOLUMN
  4762. if (depth < 1)
  4763. columnsUsed.append(label);
  4764. #endif
  4765. bool bHide = false;
  4766. if (columnsHide.length() > 0)
  4767. {
  4768. for (unsigned i = 0 ; i < columnsHide.length(); i++)
  4769. {
  4770. const char* key = columnsHide.item(i);
  4771. if (!key || strcmp(key, label))
  4772. continue;
  4773. bHide = true;
  4774. break;
  4775. }
  4776. }
  4777. #ifdef RENAMESAMECOLUMN
  4778. if (!bHide && depth > 0 && columnsUsed.length() > 0)
  4779. {
  4780. for (unsigned i = 0 ; i < columnsUsed.length(); i++)
  4781. {
  4782. const char* key = columnsUsed.item(i);
  4783. if (!key || strcmp(key, label))
  4784. continue;
  4785. StringBuffer newName(label);
  4786. newName.append("-2");
  4787. e->renameProp("/", newName.str());
  4788. break;
  4789. }
  4790. }
  4791. #endif
  4792. if (!bHide)
  4793. {
  4794. StringBuffer dataRow;
  4795. toXML(e, dataRow);
  4796. newRow.append(dataRow);
  4797. }
  4798. }
  4799. }
  4800. it->next();
  4801. }
  4802. return;
  4803. }
  4804. void CWsDfuEx::mergeDataRow(StringBuffer& newRow, StringBuffer dataRow1, StringBuffer dataRow2, StringArray& columnsHide)
  4805. {
  4806. if (dataRow1.length() < 1)
  4807. return;
  4808. if (dataRow2.length() < 1)
  4809. return;
  4810. Owned<IPropertyTree> data1 = createPTreeFromXMLString(dataRow1.str());
  4811. Owned<IPropertyTree> data2 = createPTreeFromXMLString(dataRow2.str());
  4812. if (!data1 || !data2)
  4813. return;
  4814. newRow.clear();
  4815. newRow.append("<Row>");
  4816. StringArray columnLabels;
  4817. Owned<IPropertyTreeIterator> it = data1->getElements("*");
  4818. if (it)
  4819. {
  4820. StringArray columnLabels0;
  4821. mergeDataRow(newRow, 0, it, columnLabels0, columnLabels);
  4822. }
  4823. Owned<IPropertyTreeIterator> it2 = data2->getElements("*");
  4824. if (it2)
  4825. {
  4826. mergeDataRow(newRow, 1, it2, columnsHide, columnLabels);
  4827. }
  4828. newRow.append("</Row>");
  4829. return;
  4830. }
  4831. void CWsDfuEx::browseRelatedFileSchema(IRelatedBrowseFile * file, const char* parentName, unsigned depth, StringBuffer& schemaText,
  4832. StringArray& columnsDisplay, StringArray& columnsDisplayType, StringArray& columnsHide)
  4833. {
  4834. //if (file in set of files to display or iterate)
  4835. IResultSetCursor * cursor = file->queryCursor();
  4836. if (cursor && cursor->first())
  4837. {
  4838. if (depth < 1)
  4839. {
  4840. const IResultSetMetaData & meta = cursor->queryResultSet()->getMetaData();
  4841. StringBufferAdaptor adaptor(schemaText);
  4842. meta.getXmlSchema(adaptor, false);
  4843. #ifdef TESTDATASET
  4844. schemaText.clear();
  4845. schemaText.append("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\"");
  4846. schemaText.append(" attributeFormDefault=\"unqualified\">");
  4847. schemaText.append("<xs:element name=\"Dataset\"><xs:complexType><xs:sequence minOccurs=\"0\" maxOccurs=\"unbounded\">");
  4848. schemaText.append("<xs:element name=\"Row\"><xs:complexType><xs:sequence>");
  4849. schemaText.append("<xs:element name=\"state\" type=\"string2\"/>");
  4850. schemaText.append("<xs:element name=\"rtype\" type=\"string2\"/>");
  4851. schemaText.append("<xs:element name=\"id\" type=\"string20\"/>");
  4852. schemaText.append("<xs:element name=\"seq\" type=\"xs:nonNegativeInteger\"/>");
  4853. schemaText.append("<xs:element name=\"num\" type=\"xs:nonNegativeInteger\"/>");
  4854. schemaText.append("<xs:element name=\"date\" type=\"string8\"/>");
  4855. schemaText.append("<xs:element name=\"imglength\" type=\"xs:nonNegativeInteger\"/>");
  4856. schemaText.append("<xs:element name=\"__filepos\" type=\"xs:nonNegativeInteger\"/>");
  4857. schemaText.append("</xs:sequence></xs:complexType></xs:element>");
  4858. schemaText.append("</xs:sequence></xs:complexType></xs:element>");
  4859. schemaText.append("<xs:simpleType name=\"string2\"><xs:restriction base=\"xs:string\"><xs:maxLength value=\"2\"/>");
  4860. schemaText.append("</xs:restriction></xs:simpleType>");
  4861. schemaText.append("<xs:simpleType name=\"string20\"><xs:restriction base=\"xs:string\"><xs:maxLength value=\"20\"/>");
  4862. schemaText.append("</xs:restriction></xs:simpleType>");
  4863. schemaText.append("<xs:simpleType name=\"string8\"><xs:restriction base=\"xs:string\"><xs:maxLength value=\"8\"/>");
  4864. schemaText.append("</xs:restriction></xs:simpleType>");
  4865. schemaText.append("</xs:schema>");
  4866. #endif
  4867. readColumnsForDisplay(schemaText, columnsDisplay, columnsDisplayType);
  4868. }
  4869. else
  4870. {
  4871. StringBuffer schemaText0;
  4872. const IResultSetMetaData & meta = cursor->queryResultSet()->getMetaData();
  4873. StringBufferAdaptor adaptor(schemaText0);
  4874. meta.getXmlSchema(adaptor, false);
  4875. #ifdef TESTDATASET
  4876. schemaText0.clear();
  4877. schemaText0.append("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\"");
  4878. schemaText0.append(" attributeFormDefault=\"unqualified\">");
  4879. schemaText0.append("<xs:element name=\"Dataset\"><xs:complexType><xs:sequence minOccurs=\"0\" maxOccurs=\"unbounded\">");
  4880. schemaText0.append("<xs:element name=\"Row\"><xs:complexType><xs:sequence>");
  4881. schemaText0.append("<xs:element name=\"date_first_reported\" type=\"string12\"/>");
  4882. schemaText0.append("<xs:element name=\"msa\" type=\"string8\"/>");
  4883. schemaText0.append("<xs:element name=\"sid\" type=\"string20\"/>");
  4884. schemaText0.append("<xs:element name=\"seq\" type=\"xs:nonNegativeInteger\"/>"); //not add
  4885. schemaText0.append("</xs:sequence></xs:complexType></xs:element>");
  4886. schemaText0.append("</xs:sequence></xs:complexType></xs:element>");
  4887. schemaText0.append("<xs:simpleType name=\"string12\"><xs:restriction base=\"xs:string\"><xs:maxLength value=\"12\"/>");
  4888. schemaText0.append("</xs:restriction></xs:simpleType>");
  4889. schemaText0.append("</xs:schema>");
  4890. #endif
  4891. mergeSchema(file, schemaText, schemaText0, columnsDisplay, columnsDisplayType, columnsHide);
  4892. }
  4893. if (parentName && *parentName)
  4894. {
  4895. for (unsigned i = 0;;i++)
  4896. {
  4897. IRelatedBrowseFile * next = file->queryChild(i);
  4898. if (!next)
  4899. break;
  4900. IViewRelatedFile * viewRelatedFile = next->queryDefinition();
  4901. if (!viewRelatedFile)
  4902. continue;
  4903. IDistributedFile * file = viewRelatedFile->queryDistributedFile();
  4904. if (!file)
  4905. continue;
  4906. const char* logicName0 = file->queryLogicalName();
  4907. if (logicName0 && !strcmp(logicName0, parentName))
  4908. browseRelatedFileSchema(next, NULL, depth+1, schemaText, columnsDisplay, columnsDisplayType, columnsHide);
  4909. }
  4910. }
  4911. }
  4912. return;
  4913. }
  4914. int CWsDfuEx::browseRelatedFileDataSet(double version, IRelatedBrowseFile * file, const char* parentName, unsigned depth, __int64 start, __int64& count, __int64& read,
  4915. StringArray& columnsHide, StringArray& dataSetOutput)
  4916. {
  4917. int iRet = 0;
  4918. int rows = 0;
  4919. try
  4920. {
  4921. //if (file in set of files to display or iterate)
  4922. IResultSetCursor * cursor = file->queryCursor();
  4923. if (cursor->first())
  4924. {
  4925. for(bool ok=cursor->absolute(start);ok;ok=cursor->next())
  4926. {
  4927. StringBuffer text;
  4928. StringBufferAdaptor adaptor2(text);
  4929. cursor->getXmlRow(adaptor2);
  4930. StringArray dataSetOutput0;
  4931. if (parentName && *parentName)
  4932. {
  4933. for (unsigned i = 0;;i++)
  4934. {
  4935. IRelatedBrowseFile * next = file->queryChild(i);
  4936. if (!next)
  4937. break;
  4938. IViewRelatedFile * viewRelatedFile = next->queryDefinition();
  4939. if (!viewRelatedFile)
  4940. continue;
  4941. IDistributedFile * file = viewRelatedFile->queryDistributedFile();
  4942. if (!file)
  4943. continue;
  4944. const char* logicName0 = file->queryLogicalName();
  4945. if (logicName0 && !strcmp(logicName0, parentName))
  4946. iRet = browseRelatedFileDataSet(version, next, NULL, depth+1, 0, count, read, columnsHide, dataSetOutput0);
  4947. }
  4948. }
  4949. if (dataSetOutput0.length() < 1)
  4950. {
  4951. dataSetOutput.append(text);
  4952. }
  4953. else
  4954. {
  4955. for (unsigned ii = 0; ii<dataSetOutput0.length(); ii++)
  4956. {
  4957. StringBuffer text0;
  4958. StringBuffer text1 = dataSetOutput0.item(ii);
  4959. if (text1.length() > 0)
  4960. {
  4961. mergeDataRow(text0, text, text1, columnsHide);
  4962. }
  4963. dataSetOutput.append(text0);
  4964. }
  4965. }
  4966. if (depth < 1)
  4967. {
  4968. read++;
  4969. if(read>=count)
  4970. break;
  4971. }
  4972. }
  4973. if (depth < 1)
  4974. {
  4975. if (count > read)
  4976. count = read;
  4977. }
  4978. }
  4979. }
  4980. catch(IException* e)
  4981. {
  4982. if ((version < 1.08) || (e->errorCode() != FVERR_FilterTooRestrictive))
  4983. throw e;
  4984. e->Release();
  4985. iRet = 1;
  4986. }
  4987. return iRet;
  4988. }
  4989. //sample filterBy: 340020001id1
  4990. //sample data: <XmlSchema name="myschema">...</XmlSchema><Dataset xmlSchema="myschema">...</Dataset>
  4991. int CWsDfuEx::GetIndexData(IEspContext &context, bool bSchemaOnly, const char* indexName, const char* parentName, const char* filterBy, __int64 start,
  4992. __int64& count, __int64& read, __int64& total, StringBuffer& message, StringArray& columnLabels,
  4993. StringArray& columnLabelsType, IArrayOf<IEspDFUData>& DataList, bool webDisableUppercaseTranslation)
  4994. {
  4995. if (!indexName || !*indexName)
  4996. return -1;
  4997. double version = context.getClientVersion();
  4998. StringBuffer username;
  4999. context.getUserID(username);
  5000. StringBuffer cluster;
  5001. Owned<IUserDescriptor> userdesc;
  5002. bool disableUppercaseTranslation = false;
  5003. Owned<IDistributedFile> df;
  5004. try
  5005. {
  5006. userdesc.setown(createUserDescriptor());
  5007. userdesc->set(username.str(), context.queryPassword(), context.querySignature());
  5008. df.setown(queryDistributedFileDirectory().lookup(indexName, userdesc));
  5009. if(!df)
  5010. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST,"Could not find file %s.", indexName);
  5011. //Check disableUppercaseTranslation
  5012. StringBuffer mapping;
  5013. df->getColumnMapping(mapping);
  5014. if (mapping.length() > 37 && strstr(mapping.str(), "word{set(stringlib.StringToLowerCase)}"))
  5015. disableUppercaseTranslation = true;
  5016. else if (webDisableUppercaseTranslation)
  5017. disableUppercaseTranslation = webDisableUppercaseTranslation;
  5018. else
  5019. disableUppercaseTranslation = m_disableUppercaseTranslation;
  5020. const char* wuid = df->queryAttributes().queryProp("@workunit");
  5021. if (wuid && *wuid)
  5022. {
  5023. CWUWrapper wu(wuid, context);
  5024. if (wu)
  5025. cluster.append(wu->queryClusterName());
  5026. }
  5027. }
  5028. catch (IException *e)
  5029. {
  5030. DBGLOG(e);
  5031. e->Release();
  5032. }
  5033. catch(...)
  5034. {
  5035. DBGLOG("Unknown Exception - view data file: %s", indexName);
  5036. }
  5037. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  5038. Owned<IViewFileWeb> web;
  5039. Owned<IUserDescriptor> udesc;
  5040. ISecUser * secUser = context.queryUser();
  5041. if(secUser && secUser->getName() && *secUser->getName())
  5042. {
  5043. udesc.setown(createUserDescriptor());
  5044. udesc->set(secUser->getName(), secUser->credentials().getPassword(), context.querySignature());
  5045. }
  5046. if (cluster.length())
  5047. {
  5048. web.setown(createViewFileWeb(*resultSetFactory, cluster, udesc.getLink()));
  5049. }
  5050. else if (m_clusterName.length() > 0)
  5051. {
  5052. web.setown(createViewFileWeb(*resultSetFactory, m_clusterName.str(), udesc.getLink()));
  5053. }
  5054. else
  5055. {
  5056. web.setown(createViewFileWeb(*resultSetFactory, NULL, udesc.getLink()));
  5057. }
  5058. ViewGatherOptions options;
  5059. options.primaryDepth = 100; // we want to traverse secondary->primary, but not the reverse
  5060. options.secondaryDepth = 0;
  5061. options.setPayloadFilter(true); // we're only interested in payload links
  5062. char *indexName0 = (char *) indexName;
  5063. Owned<IFileTreeBrowser> browser;
  5064. try
  5065. {
  5066. web->gatherWeb(indexName0, df, options);
  5067. browser.setown(web->createBrowseTree(indexName0));
  5068. }
  5069. catch(IException* e)
  5070. {
  5071. if ((e->errorCode() != FVERR_CouldNotResolveX) || (indexName[0] != '~'))
  5072. {
  5073. throw e;
  5074. }
  5075. else
  5076. {
  5077. e->Release();
  5078. indexName0 = (char *) (indexName+1);
  5079. web->gatherWeb(indexName0, df, options);
  5080. browser.setown(web->createBrowseTree(indexName0));
  5081. }
  5082. }
  5083. Owned<INewResultSet> result;
  5084. if (cluster && *cluster)
  5085. {
  5086. result.setown(resultSetFactory->createNewFileResultSet(indexName0, cluster));
  5087. }
  5088. else if (m_clusterName.length() > 0)
  5089. {
  5090. result.setown(resultSetFactory->createNewFileResultSet(indexName0, m_clusterName.str()));
  5091. }
  5092. else
  5093. {
  5094. result.setown(resultSetFactory->createNewFileResultSet(indexName0, NULL));
  5095. }
  5096. // Apply the filter to the root node
  5097. if (filterBy && *filterBy)
  5098. {
  5099. //Owned<IFilteredResultSet> filter = result->createFiltered();
  5100. IResultSetFilter* filter = browser->queryRootFilter();
  5101. setRootFilter(result, filterBy, filter, disableUppercaseTranslation);
  5102. ///result.setown(filter->create());
  5103. }
  5104. StringBuffer text, schemaText;
  5105. StringArray columnsHide;
  5106. browseRelatedFileSchema(browser->queryRootFile(), parentName, 0, schemaText, columnLabels, columnLabelsType, columnsHide);
  5107. text.appendf("<XmlSchema name=\"%s\">", SCHEMANAME);
  5108. text.append(schemaText);
  5109. text.append("</XmlSchema>").newline();
  5110. int iRet = 0;
  5111. if (!bSchemaOnly)
  5112. {
  5113. StringArray dataSetOutput;
  5114. iRet = browseRelatedFileDataSet(version, browser->queryRootFile(), parentName, 0, start, count, read, columnsHide, dataSetOutput);
  5115. StringBuffer dataSetText;
  5116. dataSetText.appendf("<Dataset xmlSchema=\"%s\" >", SCHEMANAME);
  5117. dataSetText.newline();
  5118. for (unsigned i = 0; i<dataSetOutput.length(); i++)
  5119. {
  5120. StringBuffer text0 = dataSetOutput.item(i);
  5121. if (text0.length() > 0)
  5122. {
  5123. dataSetText.append(text0);
  5124. dataSetText.newline();
  5125. }
  5126. }
  5127. dataSetText.append("</Dataset>");
  5128. text.append(dataSetText.str());
  5129. }
  5130. MemoryBuffer data;
  5131. struct MemoryBuffer2IStringVal : public CInterface, implements IStringVal
  5132. {
  5133. MemoryBuffer2IStringVal(MemoryBuffer & _buffer) : buffer(_buffer) {}
  5134. IMPLEMENT_IINTERFACE;
  5135. virtual const char * str() const { UNIMPLEMENTED; }
  5136. virtual void set(const char *val) { buffer.append(strlen(val),val); }
  5137. virtual void clear() { } // clearing when appending does nothing
  5138. virtual void setLen(const char *val, unsigned length) { buffer.append(length, val); }
  5139. virtual unsigned length() const { return buffer.length(); };
  5140. MemoryBuffer & buffer;
  5141. } adaptor0(data);
  5142. adaptor0.set(text.str());
  5143. data.append(0);
  5144. total=result->getNumRows();
  5145. Owned<IEspDFUData> item = createDFUData("","");
  5146. item->setName(indexName);
  5147. item->setNumRows(total);
  5148. item->setData(data.toByteArray());
  5149. DataList.append(*item.getClear());
  5150. return iRet;
  5151. }
  5152. //////////////////////HPCC Browser//////////////////////////