javaembed.cpp 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include <jni.h>
  15. #include "jexcept.hpp"
  16. #include "jthread.hpp"
  17. #include "junicode.hpp"
  18. #include "hqlplugins.hpp"
  19. #include "deftype.hpp"
  20. #include "eclhelper.hpp"
  21. #include "eclrtl.hpp"
  22. #include "eclrtl_imp.hpp"
  23. #include "rtlfield.hpp"
  24. #include "rtlds_imp.hpp"
  25. #include "jprop.hpp"
  26. #include "build-config.h"
  27. #include "roxiemem.hpp"
  28. #include "nbcd.hpp"
  29. #include "rtlformat.hpp"
  30. #include "esdl_def.hpp"
  31. #include "enginecontext.hpp"
  32. #ifndef _WIN32
  33. #include <sys/resource.h>
  34. #endif
  35. static const char * compatibleVersions[] = {
  36. "Java Embed Helper 1.0.0",
  37. NULL };
  38. static const char *version = "Java Embed Helper 1.0.0";
  39. #ifdef _DEBUG
  40. //#define TRACE_GLOBALREF
  41. //#define TRACE_CLASSFILE
  42. //#define CHECK_JNI
  43. /* Note - if you enable CHECK_JNI and see output like:
  44. * WARNING in native method: JNI call made without checking exceptions when required to from CallObjectMethodV
  45. * where for 'from' may be any of several functions, then the cause is likely to be a missing call to checkException()
  46. * after a call to the named function. One way to find the responsible call is with a breakpoint on checked_jni_CallObjectMethodV
  47. * The last time that breakpoint is hit before the warning is given should have a stack trace that tells you all you need to know.
  48. */
  49. #endif
  50. extern "C" DECL_EXPORT bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  51. {
  52. if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
  53. {
  54. ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
  55. pbx->compatibleVersions = compatibleVersions;
  56. }
  57. else if (pb->size != sizeof(ECLPluginDefinitionBlock))
  58. return false;
  59. pb->magicVersion = PLUGIN_VERSION;
  60. pb->version = version;
  61. pb->moduleName = "java";
  62. pb->ECL = NULL;
  63. pb->flags = PLUGIN_MULTIPLE_VERSIONS;
  64. pb->description = "Java Embed Helper";
  65. return true;
  66. }
  67. __declspec(noreturn) static void UNSUPPORTED(const char *feature) __attribute__((noreturn));
  68. static void UNSUPPORTED(const char *feature)
  69. {
  70. throw MakeStringException(-1, "UNSUPPORTED feature: %s not supported in java plugin", feature);
  71. }
  72. namespace javaembed {
  73. static jmethodID throwable_toString;
  74. static void forceGC(class CheckedJNIEnv* JNIenv);
  75. /**
  76. * CheckedJNIEnv is a wrapper around JNIEnv that ensures that we check for exceptions after every call (and turn them into C++ exceptions).
  77. *
  78. * It should probably be refactored to have the JNIEnv pointer as a member rather than a base class. As it stands, it's possible to cast
  79. * safely between CheckedJNIEnv * and JNIEnv*
  80. *
  81. */
  82. class CheckedJNIEnv : private JNIEnv
  83. {
  84. template<typename T> T checkException(T a) { checkException(); return a; }
  85. public:
  86. StringBuffer &getString(StringBuffer &ret, jstring s)
  87. {
  88. if (s)
  89. {
  90. const char* str = GetStringUTFChars(s, NULL);
  91. ret.append(str);
  92. ReleaseStringUTFChars(s, str);
  93. }
  94. return ret;
  95. }
  96. StringAttr &getString(StringAttr &ret, jstring s)
  97. {
  98. if (s)
  99. {
  100. const char* str = GetStringUTFChars(s, NULL);
  101. ret.set(str);
  102. ReleaseStringUTFChars(s, str);
  103. }
  104. return ret;
  105. }
  106. void checkException()
  107. {
  108. if (JNIEnv::ExceptionCheck())
  109. {
  110. jthrowable exception = JNIEnv::ExceptionOccurred();
  111. JNIEnv::ExceptionClear();
  112. jstring cause = (jstring) JNIEnv::CallObjectMethod(exception, throwable_toString);
  113. JNIEnv::ExceptionClear();
  114. const char *text = JNIEnv::GetStringUTFChars(cause, 0);
  115. VStringBuffer message("javaembed: %s", text);
  116. JNIEnv::ReleaseStringUTFChars(cause, text);
  117. JNIEnv::ExceptionClear();
  118. rtlFail(0, message);
  119. }
  120. }
  121. jclass FindClass(const char *name)
  122. {
  123. return checkException(JNIEnv::FindClass(name));
  124. }
  125. jclass FindGlobalClass(const char *name)
  126. {
  127. return (jclass) NewGlobalRef(FindClass(name), "NewGlobalRef");
  128. }
  129. void GetBooleanArrayRegion(jbooleanArray array,
  130. jsize start, jsize len, jboolean *buf) {
  131. functions->GetBooleanArrayRegion(this,array,start,len,buf);
  132. checkException();
  133. }
  134. void GetByteArrayRegion(jbyteArray array,
  135. jsize start, jsize len, jbyte *buf) {
  136. functions->GetByteArrayRegion(this,array,start,len,buf);
  137. checkException();
  138. }
  139. void GetCharArrayRegion(jcharArray array,
  140. jsize start, jsize len, jchar *buf) {
  141. functions->GetCharArrayRegion(this,array,start,len,buf);
  142. checkException();
  143. }
  144. void GetShortArrayRegion(jshortArray array,
  145. jsize start, jsize len, jshort *buf) {
  146. functions->GetShortArrayRegion(this,array,start,len,buf);
  147. checkException();
  148. }
  149. void GetIntArrayRegion(jintArray array,
  150. jsize start, jsize len, jint *buf) {
  151. functions->GetIntArrayRegion(this,array,start,len,buf);
  152. checkException();
  153. }
  154. void GetLongArrayRegion(jlongArray array,
  155. jsize start, jsize len, jlong *buf) {
  156. functions->GetLongArrayRegion(this,array,start,len,buf);
  157. checkException();
  158. }
  159. void GetFloatArrayRegion(jfloatArray array,
  160. jsize start, jsize len, jfloat *buf) {
  161. functions->GetFloatArrayRegion(this,array,start,len,buf);
  162. checkException();
  163. }
  164. void GetDoubleArrayRegion(jdoubleArray array,
  165. jsize start, jsize len, jdouble *buf) {
  166. functions->GetDoubleArrayRegion(this,array,start,len,buf);
  167. checkException();
  168. }
  169. jsize GetArrayLength(jarray array) {
  170. return checkException(functions->GetArrayLength(this,array));
  171. }
  172. jsize GetStringUTFLength(jstring str) {
  173. return checkException(functions->GetStringUTFLength(this,str));
  174. }
  175. const char* GetStringUTFChars(jstring str, jboolean *isCopy) {
  176. return checkException(functions->GetStringUTFChars(this,str,isCopy));
  177. }
  178. void ReleaseStringUTFChars(jstring str, const char* chars) {
  179. functions->ReleaseStringUTFChars(this,str,chars);
  180. checkException();
  181. }
  182. jboolean GetBooleanField(jobject obj, jfieldID fieldID)
  183. {
  184. return checkException(JNIEnv::GetBooleanField(obj,fieldID));
  185. }
  186. jobject GetObjectField(jobject obj, jfieldID fieldID)
  187. {
  188. return checkException(JNIEnv::GetObjectField(obj,fieldID));
  189. }
  190. jbyte GetByteField(jobject obj, jfieldID fieldID) {
  191. return checkException(JNIEnv::GetByteField(obj,fieldID));
  192. }
  193. jchar GetCharField(jobject obj, jfieldID fieldID) {
  194. return checkException(JNIEnv::GetCharField(obj,fieldID));
  195. }
  196. jshort GetShortField(jobject obj, jfieldID fieldID) {
  197. return checkException(JNIEnv::GetShortField(obj,fieldID));
  198. }
  199. jint GetIntField(jobject obj, jfieldID fieldID) {
  200. return checkException(JNIEnv::GetIntField(obj,fieldID));
  201. }
  202. jlong GetLongField(jobject obj, jfieldID fieldID) {
  203. return checkException(JNIEnv::GetLongField(obj,fieldID));
  204. }
  205. jfloat GetFloatField(jobject obj, jfieldID fieldID)
  206. {
  207. return checkException(JNIEnv::GetFloatField(obj,fieldID));
  208. }
  209. jdouble GetDoubleField(jobject obj, jfieldID fieldID)
  210. {
  211. return checkException(JNIEnv::GetDoubleField(obj,fieldID));
  212. }
  213. void SetObjectField(jobject obj, jfieldID fieldID, jobject val) {
  214. functions->SetObjectField(this,obj,fieldID,val);
  215. checkException();
  216. }
  217. void SetBooleanField(jobject obj, jfieldID fieldID,
  218. jboolean val) {
  219. functions->SetBooleanField(this,obj,fieldID,val);
  220. checkException();
  221. }
  222. void SetByteField(jobject obj, jfieldID fieldID,
  223. jbyte val) {
  224. functions->SetByteField(this,obj,fieldID,val);
  225. checkException();
  226. }
  227. void SetCharField(jobject obj, jfieldID fieldID,
  228. jchar val) {
  229. functions->SetCharField(this,obj,fieldID,val);
  230. checkException();
  231. }
  232. void SetShortField(jobject obj, jfieldID fieldID,
  233. jshort val) {
  234. functions->SetShortField(this,obj,fieldID,val);
  235. checkException();
  236. }
  237. void SetIntField(jobject obj, jfieldID fieldID,
  238. jint val) {
  239. functions->SetIntField(this,obj,fieldID,val);
  240. checkException();
  241. }
  242. void SetLongField(jobject obj, jfieldID fieldID,
  243. jlong val) {
  244. functions->SetLongField(this,obj,fieldID,val);
  245. checkException();
  246. }
  247. void SetFloatField(jobject obj, jfieldID fieldID,
  248. jfloat val) {
  249. functions->SetFloatField(this,obj,fieldID,val);
  250. checkException();
  251. }
  252. void SetDoubleField(jobject obj, jfieldID fieldID,
  253. jdouble val) {
  254. functions->SetDoubleField(this,obj,fieldID,val);
  255. checkException();
  256. }
  257. jstring NewString(const jchar *unicode, jsize len) {
  258. return checkException(functions->NewString(this,unicode,len));
  259. }
  260. jbooleanArray NewBooleanArray(jsize len) {
  261. return checkException(functions->NewBooleanArray(this,len));
  262. }
  263. jbyteArray NewByteArray(jsize len) {
  264. return checkException(functions->NewByteArray(this,len));
  265. }
  266. jcharArray NewCharArray(jsize len) {
  267. return checkException(functions->NewCharArray(this,len));
  268. }
  269. jshortArray NewShortArray(jsize len) {
  270. return checkException(functions->NewShortArray(this,len));
  271. }
  272. jintArray NewIntArray(jsize len) {
  273. return checkException(functions->NewIntArray(this,len));
  274. }
  275. jlongArray NewLongArray(jsize len) {
  276. return checkException(functions->NewLongArray(this,len));
  277. }
  278. jfloatArray NewFloatArray(jsize len) {
  279. return checkException(functions->NewFloatArray(this,len));
  280. }
  281. jdoubleArray NewDoubleArray(jsize len) {
  282. return checkException(functions->NewDoubleArray(this,len));
  283. }
  284. void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len,
  285. const jboolean *buf) {
  286. functions->SetBooleanArrayRegion(this,array,start,len,buf);
  287. checkException();
  288. }
  289. void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,
  290. const jbyte *buf) {
  291. functions->SetByteArrayRegion(this,array,start,len,buf);
  292. checkException();
  293. }
  294. void SetCharArrayRegion(jcharArray array, jsize start, jsize len,
  295. const jchar *buf) {
  296. functions->SetCharArrayRegion(this,array,start,len,buf);
  297. checkException();
  298. }
  299. void SetShortArrayRegion(jshortArray array, jsize start, jsize len,
  300. const jshort *buf) {
  301. functions->SetShortArrayRegion(this,array,start,len,buf);
  302. checkException();
  303. }
  304. void SetIntArrayRegion(jintArray array, jsize start, jsize len,
  305. const jint *buf) {
  306. functions->SetIntArrayRegion(this,array,start,len,buf);
  307. checkException();
  308. }
  309. void SetLongArrayRegion(jlongArray array, jsize start, jsize len,
  310. const jlong *buf) {
  311. functions->SetLongArrayRegion(this,array,start,len,buf);
  312. checkException();
  313. }
  314. void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len,
  315. const jfloat *buf) {
  316. functions->SetFloatArrayRegion(this,array,start,len,buf);
  317. checkException();
  318. }
  319. void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len,
  320. const jdouble *buf) {
  321. functions->SetDoubleArrayRegion(this,array,start,len,buf);
  322. checkException();
  323. }
  324. jobjectArray NewObjectArray(jsize len, jclass clazz,
  325. jobject init) {
  326. return checkException(functions->NewObjectArray(this,len,clazz,init));
  327. }
  328. jobject GetObjectArrayElement(jobjectArray array, jsize index) {
  329. return checkException(functions->GetObjectArrayElement(this,array,index));
  330. }
  331. void SetObjectArrayElement(jobjectArray array, jsize index,
  332. jobject val) {
  333. functions->SetObjectArrayElement(this,array,index,val);
  334. checkException();
  335. }
  336. jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) {
  337. return checkException(functions->ToReflectedField(this,cls,fieldID,isStatic));
  338. }
  339. jclass GetObjectClass(jobject obj)
  340. {
  341. return checkException(JNIEnv::GetObjectClass(obj));
  342. }
  343. jfieldID GetFieldID(jclass clazz, const char *name, const char *sig)
  344. {
  345. return checkException(JNIEnv::GetFieldID(clazz,name,sig));
  346. }
  347. jfieldID GetFieldIDUnchecked(jclass clazz, const char *name, const char *sig)
  348. {
  349. jfieldID ret = JNIEnv::GetFieldID(clazz,name,sig);
  350. ExceptionClear();
  351. return ret;
  352. }
  353. jmethodID GetMethodID(jclass clazz, const char *name, const char *sig)
  354. {
  355. return checkException(JNIEnv::GetMethodID(clazz, name, sig));
  356. }
  357. jmethodID GetStaticMethodID(jclass clazz, const char *name, const char *sig)
  358. {
  359. return checkException(JNIEnv::GetStaticMethodID(clazz, name, sig));
  360. }
  361. void CallStaticVoidMethod(jclass cls, jmethodID methodID, ...) {
  362. va_list args;
  363. va_start(args,methodID);
  364. functions->CallStaticVoidMethodV(this,cls,methodID,args);
  365. va_end(args);
  366. checkException();
  367. }
  368. jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID, ...)
  369. {
  370. va_list args;
  371. jobject result;
  372. va_start(args,methodID);
  373. result = JNIEnv::CallStaticObjectMethodV(clazz,methodID,args);
  374. va_end(args);
  375. checkException();
  376. return result;
  377. }
  378. jdouble CallDoubleMethod(jobject obj, jmethodID methodID, ...) {
  379. va_list args;
  380. jdouble result;
  381. va_start(args,methodID);
  382. result = functions->CallDoubleMethodV(this,obj,methodID,args);
  383. va_end(args);
  384. checkException();
  385. return result;
  386. }
  387. jlong CallLongMethod(jobject obj, jmethodID methodID, ...) {
  388. va_list args;
  389. jlong result;
  390. va_start(args,methodID);
  391. result = functions->CallLongMethodV(this,obj,methodID,args);
  392. va_end(args);
  393. checkException();
  394. return result;
  395. }
  396. jboolean CallBooleanMethod(jobject obj, jmethodID methodID, ...)
  397. {
  398. va_list args;
  399. jboolean result;
  400. va_start(args,methodID);
  401. result = JNIEnv::CallBooleanMethodV(obj,methodID,args);
  402. va_end(args);
  403. checkException();
  404. return result;
  405. }
  406. jobject CallObjectMethod(jobject obj, jmethodID methodID, ...)
  407. {
  408. va_list args;
  409. jobject result;
  410. va_start(args,methodID);
  411. result = JNIEnv::CallObjectMethodV(obj,methodID,args);
  412. va_end(args);
  413. checkException();
  414. return result;
  415. }
  416. jchar CallCharMethodA(jobject obj, jmethodID methodID,
  417. const jvalue * args) {
  418. return checkException(functions->CallCharMethodA(this,obj,methodID,args));
  419. }
  420. jboolean CallBooleanMethodA(jobject obj, jmethodID methodID,
  421. const jvalue * args) {
  422. return checkException(functions->CallBooleanMethodA(this,obj,methodID, args));
  423. }
  424. jshort CallShortMethodA(jobject obj, jmethodID methodID,
  425. const jvalue * args) {
  426. return checkException(functions->CallShortMethodA(this,obj,methodID,args));
  427. }
  428. jlong CallLongMethodA(jobject obj, jmethodID methodID,
  429. const jvalue * args) {
  430. return checkException(functions->CallLongMethodA(this,obj,methodID,args));
  431. }
  432. jfloat CallFloatMethodA(jobject obj, jmethodID methodID,
  433. const jvalue * args) {
  434. return checkException(functions->CallFloatMethodA(this,obj,methodID,args));
  435. }
  436. jdouble CallDoubleMethodA(jobject obj, jmethodID methodID,
  437. const jvalue * args) {
  438. return checkException(functions->CallDoubleMethodA(this,obj,methodID,args));
  439. }
  440. jint CallIntMethodA(jobject obj, jmethodID methodID,
  441. const jvalue * args) {
  442. return checkException(functions->CallIntMethodA(this,obj,methodID,args));
  443. }
  444. jbyte CallByteMethodA(jobject obj, jmethodID methodID,
  445. const jvalue * args) {
  446. return checkException(functions->CallByteMethodA(this,obj,methodID,args));
  447. }
  448. jobject CallObjectMethodA(jobject obj, jmethodID methodID,
  449. const jvalue * args) {
  450. return checkException(functions->CallObjectMethodA(this,obj,methodID,args));
  451. }
  452. void CallVoidMethodA(jobject obj, jmethodID methodID,
  453. const jvalue * args) {
  454. functions->CallVoidMethodA(this,obj,methodID,args);
  455. return checkException();
  456. }
  457. jchar CallStaticCharMethodA(jclass clazz, jmethodID methodID,
  458. const jvalue * args) {
  459. return checkException(functions->CallStaticCharMethodA(this,clazz,methodID,args));
  460. }
  461. jboolean CallStaticBooleanMethodA(jclass clazz, jmethodID methodID,
  462. const jvalue * args) {
  463. return checkException(functions->CallStaticBooleanMethodA(this,clazz,methodID, args));
  464. }
  465. jshort CallStaticShortMethodA(jclass clazz, jmethodID methodID,
  466. const jvalue * args) {
  467. return checkException(functions->CallStaticShortMethodA(this,clazz,methodID,args));
  468. }
  469. jlong CallStaticLongMethodA(jclass clazz, jmethodID methodID,
  470. const jvalue * args) {
  471. return checkException(functions->CallStaticLongMethodA(this,clazz,methodID,args));
  472. }
  473. jfloat CallStaticFloatMethodA(jclass clazz, jmethodID methodID,
  474. const jvalue * args) {
  475. return checkException(functions->CallStaticFloatMethodA(this,clazz,methodID,args));
  476. }
  477. jdouble CallStaticDoubleMethodA(jclass clazz, jmethodID methodID,
  478. const jvalue * args) {
  479. return checkException(functions->CallStaticDoubleMethodA(this,clazz,methodID,args));
  480. }
  481. jint CallStaticIntMethodA(jclass clazz, jmethodID methodID,
  482. const jvalue * args) {
  483. return checkException(functions->CallStaticIntMethodA(this,clazz,methodID,args));
  484. }
  485. jbyte CallStaticByteMethodA(jclass clazz, jmethodID methodID,
  486. const jvalue * args) {
  487. return checkException(functions->CallStaticByteMethodA(this,clazz,methodID,args));
  488. }
  489. jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID,
  490. const jvalue * args) {
  491. return checkException(functions->CallStaticObjectMethodA(this,clazz,methodID,args));
  492. }
  493. void CallStaticVoidMethodA(jclass clazz, jmethodID methodID,
  494. const jvalue * args) {
  495. functions->CallStaticVoidMethodA(this,clazz,methodID,args);
  496. return checkException();
  497. }
  498. jobject NewObjectA(jclass clazz, jmethodID methodID, const jvalue *args)
  499. {
  500. return checkException(JNIEnv::NewObjectA(clazz,methodID,args));
  501. }
  502. jobject NewObject(jclass clazz, jmethodID methodID, ...)
  503. {
  504. va_list args;
  505. jobject result;
  506. va_start(args, methodID);
  507. result = JNIEnv::NewObjectV(clazz,methodID,args);
  508. va_end(args);
  509. checkException();
  510. return result;
  511. }
  512. jstring NewStringUTF(const char *utf)
  513. {
  514. return checkException(JNIEnv::NewStringUTF(utf));
  515. }
  516. jfieldID FromReflectedField(jobject field)
  517. {
  518. return checkException(JNIEnv::FromReflectedField(field));
  519. }
  520. using JNIEnv::PushLocalFrame;
  521. using JNIEnv::PopLocalFrame;
  522. using JNIEnv::DeleteLocalRef;
  523. using JNIEnv::ExceptionClear;
  524. using JNIEnv::ExceptionCheck;
  525. #ifdef TRACE_GLOBALREF
  526. void DeleteGlobalRef(jobject val)
  527. {
  528. DBGLOG("DeleteGlobalRef %p", val);
  529. JNIEnv::DeleteGlobalRef(val);
  530. #ifdef CHECK_JNI
  531. forceGC(this);
  532. #endif
  533. }
  534. jobject NewGlobalRef(jobject val, const char *why)
  535. {
  536. jobject ret = JNIEnv::NewGlobalRef(val);
  537. DBGLOG("NewGlobalRef %p (%s) returns %p", val, why, ret);
  538. return ret;
  539. }
  540. #else
  541. inline void DeleteGlobalRef(jobject val)
  542. {
  543. JNIEnv::DeleteGlobalRef(val);
  544. }
  545. inline jobject NewGlobalRef(jobject val, const char *)
  546. {
  547. return JNIEnv::NewGlobalRef(val);
  548. }
  549. #endif
  550. };
  551. static bool printNameForClass(CheckedJNIEnv *JNIenv, jobject clsObj)
  552. {
  553. if (!clsObj)
  554. {
  555. printf("Object %p is null\n", clsObj);
  556. return false;
  557. }
  558. jclass cls = JNIenv->GetObjectClass(clsObj);
  559. jmethodID mid = JNIenv->GetMethodID(cls, "getName", "()Ljava/lang/String;");
  560. jstring strObj = (jstring) JNIenv->CallObjectMethod(clsObj, mid);
  561. const char* str = JNIenv->GetStringUTFChars(strObj, NULL);
  562. printf("class %s\n", str);
  563. bool ret = streq(str, "java.lang.Class");
  564. JNIenv->ReleaseStringUTFChars(strObj, str);
  565. return ret;
  566. }
  567. static void printClassForObject(CheckedJNIEnv *JNIenv, jobject obj)
  568. {
  569. printf("Object %p ", obj);
  570. if (!obj)
  571. {
  572. printf("is null\n");
  573. return;
  574. }
  575. jclass objClass = JNIenv->GetObjectClass(obj);
  576. jmethodID mid = JNIenv->GetMethodID(objClass, "getClass", "()Ljava/lang/Class;");
  577. jobject clsObj = JNIenv->CallObjectMethod(obj, mid);
  578. if (printNameForClass(JNIenv, clsObj))
  579. {
  580. printf(" ");
  581. printNameForClass(JNIenv, obj);
  582. }
  583. }
  584. static StringBuffer &getClassNameForObject(CheckedJNIEnv *JNIenv, StringBuffer &ret, jobject obj)
  585. {
  586. if (obj)
  587. {
  588. jclass objClass = JNIenv->GetObjectClass(obj);
  589. jmethodID mid = JNIenv->GetMethodID(objClass, "getClass", "()Ljava/lang/Class;");
  590. jobject clsObj = JNIenv->CallObjectMethod(obj, mid);
  591. jclass cls = JNIenv->GetObjectClass(clsObj);
  592. mid = JNIenv->GetMethodID(cls, "getName", "()Ljava/lang/String;");
  593. jstring strObj = (jstring) JNIenv->CallObjectMethod(clsObj, mid);
  594. const char* str = JNIenv->GetStringUTFChars(strObj, NULL);
  595. ret.append(str);
  596. JNIenv->ReleaseStringUTFChars(strObj, str);
  597. }
  598. return ret;
  599. }
  600. static jobject getClassLoader(CheckedJNIEnv *JNIenv, jclass obj)
  601. {
  602. jclass objClass = JNIenv->GetObjectClass(obj);
  603. jmethodID mid = JNIenv->GetMethodID(objClass, "getClassLoader", "()Ljava/lang/ClassLoader;");
  604. jobject classloader = JNIenv->CallObjectMethod(obj, mid);
  605. return classloader;
  606. }
  607. static CheckedJNIEnv *queryJNIEnv();
  608. // Some global objects setup at load time for efficiency and code readability
  609. static jclass customLoaderClass;
  610. static jmethodID clc_newInstance;
  611. static jmethodID clc_getSignature;
  612. static jclass hpccIteratorClass;
  613. static jmethodID hi_constructor;
  614. static jclass systemClass;
  615. static jmethodID system_gc;
  616. static jclass javaLangClassLoaderClass;
  617. static jmethodID cl_getSystemClassLoader;
  618. static jclass javaLangThreadClass;
  619. static jmethodID thread_currentThread;
  620. static jmethodID thread_getContextClassLoader;
  621. static jmethodID thread_setContextClassLoader;
  622. static jclass langObjectClass;
  623. static jmethodID object_toString;
  624. static jclass arrayListClass;
  625. static jmethodID arrayList_toArray;
  626. static jmethodID arrayList_constructor;
  627. static jmethodID arrayList_add;
  628. static jclass langStringClass;
  629. static jclass netURLClass;
  630. static jmethodID netURL_constructor;
  631. static jclass throwableClass;
  632. //static jmethodID throwable_toString; declared above
  633. static jclass langIllegalArgumentExceptionClass;
  634. static void forceGC(CheckedJNIEnv* JNIenv)
  635. {
  636. JNIenv->CallStaticVoidMethod(systemClass, system_gc);
  637. }
  638. static void setupGlobals(CheckedJNIEnv *J)
  639. {
  640. try
  641. {
  642. // Load this first as we can't report errors on the others sensibly if this one not loaded!
  643. throwableClass = J->FindGlobalClass("java/lang/Throwable");
  644. throwable_toString = J->GetMethodID(throwableClass, "toString", "()Ljava/lang/String;");
  645. systemClass = J->FindGlobalClass("java/lang/System");
  646. system_gc = J->GetStaticMethodID(systemClass, "gc", "()V");
  647. javaLangClassLoaderClass = J->FindGlobalClass("java/lang/ClassLoader");
  648. cl_getSystemClassLoader = J->GetStaticMethodID(javaLangClassLoaderClass, "getSystemClassLoader", "()Ljava/lang/ClassLoader;");
  649. javaLangThreadClass = J->FindGlobalClass("java/lang/Thread");
  650. thread_currentThread = J->GetStaticMethodID(javaLangThreadClass, "currentThread", "()Ljava/lang/Thread;");
  651. thread_getContextClassLoader = J->GetMethodID(javaLangThreadClass, "getContextClassLoader", "()Ljava/lang/ClassLoader;");
  652. thread_setContextClassLoader = J->GetMethodID(javaLangThreadClass, "setContextClassLoader", "(Ljava/lang/ClassLoader;)V");
  653. langObjectClass = J->FindGlobalClass("java/lang/Object");
  654. object_toString = J->GetMethodID(langObjectClass, "toString", "()Ljava/lang/String;");
  655. arrayListClass = J->FindGlobalClass("java/util/ArrayList");
  656. arrayList_constructor = J->GetMethodID(arrayListClass, "<init>", "()V");
  657. arrayList_add = J->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z");
  658. arrayList_toArray = J->GetMethodID(arrayListClass, "toArray", "()[Ljava/lang/Object;" );
  659. langStringClass = J->FindGlobalClass("java/lang/String");
  660. langIllegalArgumentExceptionClass = J->FindGlobalClass("java/lang/IllegalArgumentException");
  661. }
  662. catch (IException *E)
  663. {
  664. Owned<IException> e = E;
  665. throw makeWrappedExceptionV(E, E->errorCode(), "javaembed: Unable to load Java system classes - is classpath set properly?");
  666. }
  667. try
  668. {
  669. customLoaderClass = J->FindGlobalClass("com/HPCCSystems/HpccClassLoader");
  670. clc_newInstance = J->GetStaticMethodID(customLoaderClass, "newInstance","(Ljava/lang/String;Ljava/lang/ClassLoader;IJLjava/lang/String;)Lcom/HPCCSystems/HpccClassLoader;");
  671. clc_getSignature = J->GetStaticMethodID(customLoaderClass, "getSignature","(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/String;");
  672. hpccIteratorClass = J->FindGlobalClass("com/HPCCSystems/HpccUtils");
  673. hi_constructor = J->GetMethodID(hpccIteratorClass, "<init>", "(JLjava/lang/String;)V");
  674. }
  675. catch (IException *E)
  676. {
  677. Owned<IException> e = E;
  678. throw makeWrappedExceptionV(E, E->errorCode(), "javaembed: Unable to find HPCC classes - is classpath set properly?");
  679. }
  680. }
  681. static StringAttr & getSignature(StringAttr &ret, CheckedJNIEnv *J, jclass clazz, const char *funcName)
  682. {
  683. jstring result = (jstring) J->CallStaticObjectMethod(customLoaderClass, clc_getSignature, clazz, J->NewStringUTF(funcName));
  684. return J->getString(ret, result);
  685. }
  686. /**
  687. * The following classes are used to ensure that the code in loadFunction that creates an instance
  688. * that is shared between multiple callers is only called on one thread, while other threads will wait
  689. * and use the instance created by the first thread.
  690. *
  691. */
  692. class PersistedObject : public MappingBase
  693. {
  694. public:
  695. PersistedObject(const char *_name) : name(_name) {}
  696. CriticalSection crit;
  697. jobject instance = nullptr;
  698. StringAttr name;
  699. virtual const void * getKey() const { return name; }
  700. };
  701. class PersistedObjectCriticalBlock
  702. {
  703. PersistedObject *obj = nullptr;
  704. public:
  705. inline PersistedObjectCriticalBlock()
  706. {
  707. }
  708. inline ~PersistedObjectCriticalBlock()
  709. {
  710. if (obj)
  711. obj->crit.leave();
  712. }
  713. inline void enter(PersistedObject *_obj)
  714. {
  715. // Note that the object should be locked before we are called
  716. assertex(!obj);
  717. obj = _obj;
  718. }
  719. inline void leave(jobject instance = nullptr)
  720. {
  721. if (obj)
  722. {
  723. if (instance)
  724. obj->instance = instance;
  725. obj->crit.leave();
  726. obj = nullptr;
  727. }
  728. }
  729. inline bool locked()
  730. {
  731. return obj != nullptr;
  732. }
  733. jobject getInstance()
  734. {
  735. assertex(obj);
  736. return obj->instance;
  737. }
  738. };
  739. // Use a global object to ensure that the Java VM is initialized once only.
  740. // We would like to create it lazily for two reasons:
  741. // 1. So that we only get a JVM if we need one (even if we have loaded the plugin)
  742. // 2. It's important for the JVM to be initialized AFTER we have set up signal handlers, as it
  743. // likes to set its own (in particular, it seems to intercept and ignore some SIGSEGV during the
  744. // garbage collection).
  745. // Unfortunately, it seems that the design of the JNI interface is such that JNI_CreateJavaVM has to be called on the 'main thread'.
  746. // So we can't achieve 1, and 2 requires that we create via the INIT_MODULE mechanism (rather than just a static object), and that
  747. // any engines that call InitModuleObjects() or load plugins dynamically do so AFTER setting any signal handlers or calling
  748. // EnableSEHtoExceptionMapping
  749. //
  750. static class JavaGlobalState
  751. {
  752. public:
  753. JavaGlobalState() : persistedObjects(false)
  754. {
  755. JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
  756. StringArray optionStrings;
  757. const char* origPath = getenv("CLASSPATH");
  758. StringBuffer newPath;
  759. newPath.append("-Djava.class.path=");
  760. if (origPath && *origPath)
  761. {
  762. newPath.append(origPath).append(ENVSEPCHAR);
  763. }
  764. const IProperties &conf = queryEnvironmentConf();
  765. if (conf.hasProp("classpath"))
  766. {
  767. conf.getProp("classpath", newPath);
  768. newPath.append(ENVSEPCHAR);
  769. }
  770. else
  771. {
  772. newPath.append(INSTALL_DIR).append(PATHSEPCHAR).append("classes").append(ENVSEPCHAR);
  773. }
  774. newPath.append(".");
  775. optionStrings.append(newPath);
  776. if (conf.hasProp("jvmlibpath"))
  777. {
  778. StringBuffer libPath;
  779. libPath.append("-Djava.library.path=");
  780. conf.getProp("jvmlibpath", libPath);
  781. optionStrings.append(libPath);
  782. }
  783. // Options we should set (but allow for override with jvmoptions below)
  784. optionStrings.append("-XX:-UseLargePages");
  785. if (conf.hasProp("jvmoptions"))
  786. {
  787. // Use space as field sep as ':' and ';' are valid
  788. optionStrings.appendList(conf.queryProp("jvmoptions"), " ");
  789. }
  790. // Options we know we always want set
  791. optionStrings.append("-Xrs");
  792. #ifdef RLIMIT_STACK
  793. // JVM has a habit of reducing the stack limit on main thread to 1M - probably dates back to when it was actually an increase...
  794. StringBuffer stackOption("-Xss");
  795. struct rlimit limit;
  796. rlim_t slim = 0;
  797. if (getrlimit (RLIMIT_STACK, &limit)==0)
  798. slim = limit.rlim_cur;
  799. if (!slim)
  800. slim = 8*1024*1024;
  801. if (slim >= 1*1024*1024)
  802. {
  803. stackOption.append((__uint64) slim);
  804. optionStrings.append(stackOption);
  805. }
  806. #endif
  807. // These may be useful for debugging
  808. #ifdef CHECK_JNI
  809. optionStrings.append("-Xcheck:jni");
  810. optionStrings.append("-verbose:jni");
  811. optionStrings.append("-XX:+TraceClassLoading");
  812. #endif
  813. JavaVMOption* options = new JavaVMOption[optionStrings.length()];
  814. ForEachItemIn(idx, optionStrings)
  815. {
  816. // DBGLOG("javaembed: Setting JVM option: %s",(char *)optionStrings.item(idx));
  817. options[idx].optionString = (char *) optionStrings.item(idx);
  818. options[idx].extraInfo = NULL;
  819. }
  820. vm_args.nOptions = optionStrings.length();
  821. vm_args.options = options;
  822. vm_args.ignoreUnrecognized = true;
  823. vm_args.version = JNI_VERSION_1_8;
  824. /* load and initialize a Java VM, return a JNI interface pointer in env */
  825. JNIEnv *env; /* receives pointer to native method interface */
  826. int createResult = JNI_CreateJavaVM(&javaVM, (void**)&env, &vm_args);
  827. delete [] options;
  828. if (createResult != 0)
  829. throw MakeStringException(0, "javaembed: Unable to initialize JVM (%d)",createResult);
  830. setupGlobals((CheckedJNIEnv *) env);
  831. // DBGLOG("JNI environment version %x loaded", env->GetVersion()); // Comes out a bit too early
  832. }
  833. ~JavaGlobalState()
  834. {
  835. /* We could release global persisted classes here but not a lot of point. Code would look something like this:
  836. HashIterator it(persistedObjects);
  837. ForEach(it)
  838. {
  839. IMapping &entry = it.query();
  840. jobject *pObj = persistedObjects.mapToValue(&entry);
  841. if (pClass)
  842. queryJNIEnv()->DeleteGlobalRef(*pObj);
  843. }
  844. */
  845. // This function is never called anyway...
  846. // We don't attempt to destroy the Java VM, as it's buggy...
  847. }
  848. PersistedObject *getGlobalObject(CheckedJNIEnv *JNIenv, const char *name)
  849. {
  850. PersistedObject *p;
  851. {
  852. CriticalBlock b(hashCrit);
  853. p = persistedObjects.find(name);
  854. if (!p)
  855. {
  856. p = new PersistedObject(name);
  857. persistedObjects.replaceOwn(*p);
  858. }
  859. }
  860. p->crit.enter(); // outside the hashCrit block, otherwise I think there is a possibility of deadlock
  861. return p;
  862. }
  863. void doUnregister(const char *key)
  864. {
  865. CriticalBlock b(hashCrit);
  866. PersistedObject *p = persistedObjects.find(key);
  867. if (p && p->instance)
  868. {
  869. queryJNIEnv()->DeleteGlobalRef(p->instance);
  870. #ifdef CHECK_JNI
  871. forceGC(queryJNIEnv());
  872. #endif
  873. }
  874. persistedObjects.remove(key);
  875. }
  876. static void unregister(const char *key);
  877. JavaVM *javaVM; /* denotes a Java VM */
  878. private:
  879. CriticalSection hashCrit;
  880. StringMapOf<PersistedObject> persistedObjects;
  881. } *globalState;
  882. void JavaGlobalState::unregister(const char *key)
  883. {
  884. // Remove a class that was persisted via : PERSIST options - it has come to the end of its life
  885. globalState->doUnregister(key);
  886. }
  887. static StringBuffer helperLibraryName;
  888. #ifdef _WIN32
  889. EXTERN_C IMAGE_DOS_HEADER __ImageBase;
  890. #endif
  891. MODULE_INIT(INIT_PRIORITY_STANDARD)
  892. {
  893. globalState = new JavaGlobalState;
  894. // Make sure we are never unloaded (as JVM does not support it)
  895. // we do this by doing a dynamic load of the javaembed library
  896. #ifdef _WIN32
  897. char ln[_MAX_PATH];
  898. ::GetModuleFileName((HINSTANCE)&__ImageBase, ln, _MAX_PATH);
  899. if (strstr(path, "javaembed"))
  900. {
  901. HINSTANCE h = LoadSharedObject(ln, false, false);
  902. helperLibraryName.set(ln);
  903. DBGLOG("LoadSharedObject returned %p", h);
  904. }
  905. #else
  906. if (findLoadedModule(helperLibraryName, "javaembed"))
  907. {
  908. HINSTANCE h = LoadSharedObject(helperLibraryName, false, false);
  909. // Deliberately leak this handle
  910. }
  911. #endif
  912. return true;
  913. }
  914. MODULE_EXIT()
  915. {
  916. // We don't attempt to destroy the Java VM, as it's buggy...
  917. // delete globalState;
  918. // globalState = NULL;
  919. }
  920. static void checkType(type_t javatype, size32_t javasize, type_t ecltype, size32_t eclsize)
  921. {
  922. if (javatype != ecltype || javasize != eclsize)
  923. throw MakeStringException(0, "javaembed: Type mismatch"); // MORE - could provide some details!
  924. }
  925. enum PersistMode
  926. {
  927. persistNone,
  928. persistThread,
  929. persistWorkunit,
  930. persistQuery,
  931. persistGlobal
  932. };
  933. static PersistMode getPersistMode(const char *val, StringAttr &globalScope)
  934. {
  935. StringAttr trimmed;
  936. const char *colon = strchr(val, ':');
  937. if (colon)
  938. {
  939. globalScope.set(colon+1);
  940. trimmed.set(val, colon-val);
  941. val = trimmed;
  942. }
  943. if (isEmptyString(val) || strieq(val, "none"))
  944. return persistNone;
  945. else if (strieq(val, "thread"))
  946. return persistThread;
  947. else if (strieq(val, "workunit"))
  948. return persistWorkunit;
  949. else if (strieq(val, "query"))
  950. return persistQuery;
  951. else if (strieq(val, "global"))
  952. return persistGlobal;
  953. else
  954. throw MakeStringException(MSGAUD_user, 0, "javaembed: Unrecognized persist mode %s", val);
  955. }
  956. //-------------------------------------------
  957. // A JavaObject accessor has common functionality shared by both the builders below (Java-> ECL and ECL->Java)
  958. class JavaObjectAccessor : public CInterface
  959. {
  960. protected:
  961. JavaObjectAccessor(CheckedJNIEnv *_JNIenv, const RtlFieldInfo *_outerRow, jobject _row)
  962. : JNIenv(_JNIenv), row(_row), outerRow(_outerRow), idx(0), limit(0), inSet(false), inDataSet(false)
  963. {
  964. Class = (jclass) JNIenv->NewGlobalRef(JNIenv->GetObjectClass(row), "Class");
  965. }
  966. JavaObjectAccessor(CheckedJNIEnv *_JNIenv, const RtlFieldInfo *_outerRow, jclass _Class)
  967. : JNIenv(_JNIenv), outerRow(_outerRow), idx(0), limit(0), inSet(false), inDataSet(false)
  968. {
  969. row = NULL;
  970. Class = (jclass) JNIenv->NewGlobalRef(_Class, "Class");
  971. }
  972. ~JavaObjectAccessor()
  973. {
  974. // Unwind anything left on the stack (in case we had exceptions), to make sure the Class we release is the global one
  975. if (stack.length())
  976. Class = (jclass) stack.item(0);
  977. if (Class)
  978. JNIenv->DeleteGlobalRef(Class);
  979. }
  980. void push()
  981. {
  982. stack.append(Class);
  983. stack.append(row);
  984. }
  985. void pop()
  986. {
  987. row = (jobject) stack.popGet();
  988. Class = (jclass) stack.popGet();
  989. }
  990. jfieldID checkCharField(const RtlFieldInfo * field)
  991. {
  992. return JNIenv->GetFieldIDUnchecked(Class, field->name, inSet ? "[C" : "C");
  993. }
  994. jfieldID getFieldId(const RtlFieldInfo * field, const char *sig, const char *expected)
  995. {
  996. // MORE - if we are going to stream a dataset we really should be caching these somehow
  997. try
  998. {
  999. jfieldID fieldId = 0;
  1000. if (sig)
  1001. {
  1002. if (inSet)
  1003. {
  1004. VStringBuffer arraySig("[%s", sig);
  1005. fieldId = JNIenv->GetFieldID(Class, field->name, arraySig.str());
  1006. }
  1007. else
  1008. fieldId = JNIenv->GetFieldID(Class, field->name, sig);
  1009. }
  1010. else
  1011. {
  1012. // Do it the hard way via reflection API
  1013. // Equivalent java:
  1014. // Field field = object.getClass().getDeclaredField(fieldName);
  1015. jclass classClass =JNIenv->GetObjectClass(Class);
  1016. jmethodID getDeclaredField = JNIenv->GetMethodID(classClass, "getDeclaredField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;" );
  1017. jstring fieldName = JNIenv->NewStringUTF(field->name);
  1018. jobject reflectedField = JNIenv->CallObjectMethod(Class, getDeclaredField, fieldName);
  1019. fieldId = JNIenv->FromReflectedField(reflectedField);
  1020. }
  1021. return fieldId;
  1022. }
  1023. catch (IException *E)
  1024. {
  1025. ::Release(E);
  1026. throw MakeStringException(0, "javaembed: Unable to retrieve field %s of type %s", field->name, expected);
  1027. }
  1028. }
  1029. CheckedJNIEnv *JNIenv;
  1030. jobject row;
  1031. const RtlFieldInfo *outerRow;
  1032. jclass Class;
  1033. ConstPointerArray stack;
  1034. unsigned idx;
  1035. UnsignedArray idxStack;
  1036. unsigned limit;
  1037. bool inSet;
  1038. bool inDataSet;
  1039. };
  1040. // A JavaRowBuilder object is used to construct an ECL row from a Java object
  1041. class JavaRowBuilder : public JavaObjectAccessor, implements IFieldSource
  1042. {
  1043. public:
  1044. IMPLEMENT_IINTERFACE;
  1045. JavaRowBuilder(CheckedJNIEnv *_JNIenv, const RtlFieldInfo *_outerRow, jobject _row)
  1046. : JavaObjectAccessor(_JNIenv, _outerRow, _row)
  1047. {
  1048. }
  1049. virtual bool getBooleanResult(const RtlFieldInfo *field)
  1050. {
  1051. jboolean b;
  1052. if (inSet)
  1053. {
  1054. JNIenv->GetBooleanArrayRegion((jbooleanArray) row, idx, 1, &b);
  1055. }
  1056. else
  1057. {
  1058. jfieldID fieldId = getFieldId(field, "Z", "boolean");
  1059. b = JNIenv->GetBooleanField(row, fieldId);
  1060. }
  1061. return b;
  1062. }
  1063. virtual void getDataResult(const RtlFieldInfo *field, size32_t &__len, void * &__result)
  1064. {
  1065. jbyteArray array;
  1066. if (inSet)
  1067. {
  1068. array = (jbyteArray) JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
  1069. }
  1070. else
  1071. {
  1072. jfieldID fieldId = getFieldId(field, "[B", "DATA");
  1073. array = (jbyteArray) JNIenv->GetObjectField(row, fieldId);
  1074. }
  1075. __len = (array != NULL ? JNIenv->GetArrayLength(array) : 0);
  1076. __result = (__len > 0 ? rtlMalloc(__len) : NULL);
  1077. if (__result)
  1078. JNIenv->GetByteArrayRegion(array, 0, __len, (jbyte *) __result);
  1079. }
  1080. virtual double getRealResult(const RtlFieldInfo *field)
  1081. {
  1082. double d;
  1083. if (inSet)
  1084. {
  1085. float f;
  1086. switch (field->size(NULL, NULL))
  1087. {
  1088. case 4:
  1089. JNIenv->GetFloatArrayRegion((jfloatArray) row, idx, 1, &f);
  1090. d = f;
  1091. break;
  1092. case 8:
  1093. JNIenv->GetDoubleArrayRegion((jdoubleArray) row, idx, 1, &d);
  1094. break;
  1095. default:
  1096. throwUnexpected();
  1097. }
  1098. }
  1099. else
  1100. {
  1101. jfieldID fieldId;
  1102. switch (field->size(NULL, NULL))
  1103. {
  1104. case 4:
  1105. fieldId = getFieldId(field, "F", "float");
  1106. d = JNIenv->GetFloatField(row, fieldId);
  1107. break;
  1108. case 8:
  1109. fieldId = getFieldId(field, "D", "double");
  1110. d = JNIenv->GetDoubleField(row, fieldId);
  1111. break;
  1112. default:
  1113. throwUnexpected();
  1114. }
  1115. }
  1116. return d;
  1117. }
  1118. virtual __int64 getSignedResult(const RtlFieldInfo *field)
  1119. {
  1120. __int64 ret;
  1121. if (inSet)
  1122. {
  1123. jbyte b;
  1124. jshort s;
  1125. jint i;
  1126. jlong l;
  1127. switch (field->size(NULL, NULL))
  1128. {
  1129. case 1:
  1130. JNIenv->GetByteArrayRegion((jbyteArray) row, idx, 1, &b);
  1131. ret = b;
  1132. break;
  1133. case 2:
  1134. JNIenv->GetShortArrayRegion((jshortArray) row, idx, 1, &s);
  1135. ret = s;
  1136. break;
  1137. case 4:
  1138. JNIenv->GetIntArrayRegion((jintArray) row, idx, 1, &i);
  1139. ret = i;
  1140. break;
  1141. case 8:
  1142. JNIenv->GetLongArrayRegion((jlongArray) row, idx, 1, &l);
  1143. ret = l;
  1144. break;
  1145. default:
  1146. UNSUPPORTED("non-standard integer sizes");
  1147. }
  1148. }
  1149. else
  1150. {
  1151. jfieldID fieldId;
  1152. switch (field->size(NULL, NULL))
  1153. {
  1154. case 1:
  1155. fieldId = getFieldId(field, "B", "byte");
  1156. ret = JNIenv->GetByteField(row, fieldId);
  1157. break;
  1158. case 2:
  1159. fieldId = getFieldId(field, "S", "short");
  1160. ret = JNIenv->GetShortField(row, fieldId);
  1161. break;
  1162. case 4:
  1163. fieldId = getFieldId(field, "I", "int");
  1164. ret = JNIenv->GetIntField(row, fieldId);
  1165. break;
  1166. case 8:
  1167. fieldId = getFieldId(field, "J", "long");
  1168. ret = JNIenv->GetLongField(row, fieldId);
  1169. break;
  1170. default:
  1171. UNSUPPORTED("non-standard integer sizes");
  1172. }
  1173. }
  1174. return ret;
  1175. }
  1176. virtual unsigned __int64 getUnsignedResult(const RtlFieldInfo *field)
  1177. {
  1178. UNSUPPORTED("unsigned fields"); // No unsigned types in Java
  1179. }
  1180. virtual void getStringResult(const RtlFieldInfo *field, size32_t &__len, char * &__result)
  1181. {
  1182. jstring result;
  1183. if (inSet)
  1184. {
  1185. // MORE - set of string1 mapping to Java array of char ? Not sure it's worth it.
  1186. result = (jstring) JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
  1187. }
  1188. else
  1189. {
  1190. if (field->isFixedSize() && field->size(NULL, NULL)==1)
  1191. {
  1192. // See if there's a char field
  1193. jfieldID charFieldId = checkCharField(field);
  1194. if (charFieldId)
  1195. {
  1196. jchar resultChar = JNIenv->GetCharField(row, charFieldId);
  1197. rtlUnicodeToStrX(__len, __result, 1, &resultChar);
  1198. return;
  1199. }
  1200. }
  1201. jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
  1202. result = (jstring) JNIenv->GetObjectField(row, fieldId);
  1203. }
  1204. if (!result)
  1205. {
  1206. __len = 0;
  1207. __result = NULL;
  1208. return;
  1209. }
  1210. size_t size = JNIenv->GetStringUTFLength(result); // in bytes
  1211. const char *text = JNIenv->GetStringUTFChars(result, NULL);
  1212. size32_t chars = rtlUtf8Length(size, text);
  1213. rtlUtf8ToStrX(__len, __result, chars, text);
  1214. JNIenv->ReleaseStringUTFChars(result, text);
  1215. JNIenv->DeleteLocalRef(result);
  1216. }
  1217. virtual void getUTF8Result(const RtlFieldInfo *field, size32_t &__len, char * &__result)
  1218. {
  1219. jstring result;
  1220. if (inSet)
  1221. {
  1222. // MORE - set of string1 mapping to Java array of char ? Not sure it's worth it.
  1223. result = (jstring) JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
  1224. }
  1225. else
  1226. {
  1227. if (field->isFixedSize() && field->size(NULL, NULL)==1)
  1228. {
  1229. // See if there's a char field
  1230. jfieldID charFieldId = checkCharField(field);
  1231. if (charFieldId)
  1232. {
  1233. jchar resultChar = JNIenv->GetCharField(row, charFieldId);
  1234. rtlUnicodeToUtf8X(__len, __result, 1, &resultChar);
  1235. return;
  1236. }
  1237. }
  1238. jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
  1239. result = (jstring) JNIenv->GetObjectField(row, fieldId);
  1240. }
  1241. if (!result)
  1242. {
  1243. __len = 0;
  1244. __result = NULL;
  1245. return;
  1246. }
  1247. size_t size = JNIenv->GetStringUTFLength(result); // in bytes
  1248. const char *text = JNIenv->GetStringUTFChars(result, NULL);
  1249. size32_t chars = rtlUtf8Length(size, text);
  1250. rtlUtf8ToUtf8X(__len, __result, chars, text);
  1251. JNIenv->ReleaseStringUTFChars(result, text);
  1252. JNIenv->DeleteLocalRef(result);
  1253. }
  1254. virtual void getUnicodeResult(const RtlFieldInfo *field, size32_t &__len, UChar * &__result)
  1255. {
  1256. jstring result;
  1257. if (inSet)
  1258. {
  1259. // MORE - set of string1 mapping to Java array of char ? Not sure it's worth it.
  1260. result = (jstring) JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
  1261. }
  1262. else
  1263. {
  1264. if (field->isFixedSize() && field->size(NULL, NULL)==1)
  1265. {
  1266. // See if there's a char field
  1267. jfieldID charFieldId = checkCharField(field);
  1268. if (charFieldId)
  1269. {
  1270. jchar resultChar = JNIenv->GetCharField(row, charFieldId);
  1271. rtlUnicodeToUnicodeX(__len, __result, 1, &resultChar);
  1272. return;
  1273. }
  1274. }
  1275. jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
  1276. result = (jstring) JNIenv->GetObjectField(row, fieldId);
  1277. }
  1278. if (!result)
  1279. {
  1280. __len = 0;
  1281. __result = NULL;
  1282. return;
  1283. }
  1284. size_t size = JNIenv->GetStringUTFLength(result); // in bytes
  1285. const char *text = JNIenv->GetStringUTFChars(result, NULL);
  1286. size32_t chars = rtlUtf8Length(size, text);
  1287. rtlUtf8ToUnicodeX(__len, __result, chars, text);
  1288. JNIenv->ReleaseStringUTFChars(result, text);
  1289. JNIenv->DeleteLocalRef(result);
  1290. }
  1291. virtual void getDecimalResult(const RtlFieldInfo *field, Decimal &value)
  1292. {
  1293. double ret = getRealResult(field);
  1294. value.setReal(ret);
  1295. }
  1296. virtual void processBeginSet(const RtlFieldInfo * field, bool &isAll)
  1297. {
  1298. isAll = false; // No concept of an 'all' set in Java
  1299. push();
  1300. jfieldID fieldId = getFieldId(field, NULL, "object"); // We assume it will be an array, but not sure of what...
  1301. row = JNIenv->GetObjectField(row, fieldId);
  1302. inSet = true;
  1303. idx = -1; // First call to next() increments it to 0
  1304. limit = row != NULL ? JNIenv->GetArrayLength((jarray) row) : 0;
  1305. }
  1306. virtual bool processNextSet(const RtlFieldInfo * field)
  1307. {
  1308. assertex(inSet);
  1309. idx++;
  1310. return idx < limit;
  1311. }
  1312. virtual void processBeginDataset(const RtlFieldInfo * field)
  1313. {
  1314. push();
  1315. jfieldID fieldId = getFieldId(field, NULL, "object"); // We assume it will be an array, but not sure of what...
  1316. row = JNIenv->GetObjectField(row, fieldId);
  1317. inDataSet = true;
  1318. idx = -1; // First call to next() increments it to 0
  1319. limit = row != NULL ? JNIenv->GetArrayLength((jarray) row) : 0;
  1320. }
  1321. virtual void processBeginRow(const RtlFieldInfo * field)
  1322. {
  1323. if (field != outerRow)
  1324. {
  1325. push();
  1326. if (inDataSet)
  1327. {
  1328. row = JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
  1329. }
  1330. else
  1331. {
  1332. jfieldID fieldId = getFieldId(field, NULL, "object");
  1333. row = JNIenv->GetObjectField(row, fieldId);
  1334. }
  1335. if (!row)
  1336. rtlFail(0, "javaembed: child dataset object should not be NULL");
  1337. Class = JNIenv->GetObjectClass(row);
  1338. }
  1339. }
  1340. virtual bool processNextRow(const RtlFieldInfo * field)
  1341. {
  1342. assertex(inDataSet);
  1343. idx++;
  1344. return idx < limit;
  1345. }
  1346. virtual void processEndSet(const RtlFieldInfo * field)
  1347. {
  1348. inSet = false;
  1349. JNIenv->DeleteLocalRef(row);
  1350. pop();
  1351. }
  1352. virtual void processEndDataset(const RtlFieldInfo * field)
  1353. {
  1354. inDataSet = false;
  1355. JNIenv->DeleteLocalRef(row);
  1356. pop();
  1357. }
  1358. virtual void processEndRow(const RtlFieldInfo * field)
  1359. {
  1360. if (field != outerRow)
  1361. {
  1362. JNIenv->DeleteLocalRef(row);
  1363. JNIenv->DeleteLocalRef(Class);
  1364. pop();
  1365. }
  1366. }
  1367. };
  1368. //-------------------------------------------
  1369. // A JavaObjectBuilder object is used to construct a Java object from an ECL row
  1370. class JavaObjectBuilder : public JavaObjectAccessor, implements IFieldProcessor
  1371. {
  1372. public:
  1373. IMPLEMENT_IINTERFACE;
  1374. JavaObjectBuilder(CheckedJNIEnv *_JNIenv, const RtlFieldInfo *_outerRow, jclass _Class)
  1375. : JavaObjectAccessor(_JNIenv, _outerRow, _Class)
  1376. {
  1377. setConstructor();
  1378. }
  1379. virtual void processString(unsigned numchars, const char *text, const RtlFieldInfo * field)
  1380. {
  1381. if (field->isFixedSize() && field->size(NULL, NULL)==1 && !inSet) // SET OF STRING1 is not mapped to array of char...
  1382. {
  1383. // See if there's a char field
  1384. jfieldID charFieldId = checkCharField(field);
  1385. if (charFieldId)
  1386. {
  1387. assertex(numchars==1);
  1388. jchar c;
  1389. rtlStrToUnicode(1, &c, 1, text);
  1390. JNIenv->SetCharField(row, charFieldId, c);
  1391. return;
  1392. }
  1393. }
  1394. jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
  1395. size32_t numchars16;
  1396. rtlDataAttr unicode16;
  1397. rtlStrToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
  1398. jstring value = JNIenv->NewString(unicode16.getustr(), numchars16);
  1399. if (inSet)
  1400. JNIenv->SetObjectArrayElement((jobjectArray) row, idx, value);
  1401. else
  1402. JNIenv->SetObjectField(row, fieldId, value);
  1403. JNIenv->DeleteLocalRef(value);
  1404. }
  1405. virtual void processBool(bool value, const RtlFieldInfo * field)
  1406. {
  1407. jfieldID fieldId = getFieldId(field, "Z", "boolean");
  1408. JNIenv->SetBooleanField(row, fieldId, value);
  1409. }
  1410. virtual void processData(unsigned len, const void *value, const RtlFieldInfo * field)
  1411. {
  1412. jfieldID fieldId = getFieldId(field, "[B", "data");
  1413. jbyteArray javaData = JNIenv->NewByteArray(len);
  1414. JNIenv->SetByteArrayRegion(javaData, 0, len, (jbyte *) value);
  1415. if (inSet)
  1416. JNIenv->SetObjectArrayElement((jobjectArray) row, idx, javaData);
  1417. else
  1418. JNIenv->SetObjectField(row, fieldId, javaData);
  1419. }
  1420. virtual void processInt(__int64 value, const RtlFieldInfo * field)
  1421. {
  1422. jfieldID fieldId;
  1423. switch (field->size(NULL, NULL))
  1424. {
  1425. case 1:
  1426. fieldId = getFieldId(field, "B", "byte");
  1427. JNIenv->SetByteField(row, fieldId, value);
  1428. break;
  1429. case 2:
  1430. fieldId = getFieldId(field, "S", "short");
  1431. JNIenv->SetShortField(row, fieldId, value);
  1432. break;
  1433. case 4:
  1434. fieldId = getFieldId(field, "I", "int");
  1435. JNIenv->SetIntField(row, fieldId, value);
  1436. break;
  1437. case 8:
  1438. fieldId = getFieldId(field, "J", "long");
  1439. JNIenv->SetLongField(row, fieldId, value);
  1440. break;
  1441. default:
  1442. UNSUPPORTED("non-standard integer sizes");
  1443. break;
  1444. }
  1445. }
  1446. virtual void processUInt(unsigned __int64 value, const RtlFieldInfo * field)
  1447. {
  1448. UNSUPPORTED("unsigned fields"); // No unsigned types in Java
  1449. }
  1450. virtual void processReal(double value, const RtlFieldInfo * field)
  1451. {
  1452. jfieldID fieldId;
  1453. switch (field->size(NULL, NULL))
  1454. {
  1455. case 4:
  1456. fieldId = getFieldId(field, "F", "float");
  1457. JNIenv->SetFloatField(row, fieldId, (float) value);
  1458. break;
  1459. case 8:
  1460. fieldId = getFieldId(field, "D", "double");
  1461. JNIenv->SetDoubleField(row, fieldId, value);
  1462. break;
  1463. default:
  1464. throwUnexpected();
  1465. }
  1466. }
  1467. virtual void processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  1468. {
  1469. // we could map to doubles, but probably better to let the ECL programmer do that themselves
  1470. UNSUPPORTED("DECIMAL fields");
  1471. }
  1472. virtual void processUDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  1473. {
  1474. UNSUPPORTED("UDECIMAL fields");
  1475. }
  1476. virtual void processUnicode(unsigned numchars, const UChar *text, const RtlFieldInfo * field)
  1477. {
  1478. jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
  1479. jstring value = JNIenv->NewString(text, numchars);
  1480. if (inSet)
  1481. JNIenv->SetObjectArrayElement((jobjectArray) row, idx, value);
  1482. else
  1483. JNIenv->SetObjectField(row, fieldId, value);
  1484. JNIenv->DeleteLocalRef(value);
  1485. }
  1486. virtual void processQString(unsigned len, const char *value, const RtlFieldInfo * field)
  1487. {
  1488. size32_t charCount;
  1489. rtlDataAttr text;
  1490. rtlQStrToStrX(charCount, text.refstr(), len, value);
  1491. processString(charCount, text.getstr(), field);
  1492. }
  1493. virtual void processUtf8(unsigned numchars, const char *text, const RtlFieldInfo * field)
  1494. {
  1495. jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
  1496. size32_t numchars16;
  1497. rtlDataAttr unicode16;
  1498. rtlUtf8ToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
  1499. jstring value = JNIenv->NewString(unicode16.getustr(), numchars16);
  1500. if (inSet)
  1501. JNIenv->SetObjectArrayElement((jobjectArray) row, idx, value);
  1502. else
  1503. JNIenv->SetObjectField(row, fieldId, value);
  1504. JNIenv->DeleteLocalRef(value);
  1505. }
  1506. virtual bool processBeginSet(const RtlFieldInfo * field, unsigned numElems, bool isAll, const byte *data)
  1507. {
  1508. push();
  1509. idx = 0;
  1510. limit = numElems;
  1511. const char *javaTypeSignature = NULL;
  1512. bool processElements = false;
  1513. // row needs to be created as an array of <whatever>
  1514. if (isAll)
  1515. UNSUPPORTED("ALL sets");
  1516. const RtlTypeInfo *childType = field->type->queryChildType();
  1517. jobject newRow;
  1518. switch(childType->fieldType & RFTMkind)
  1519. {
  1520. case type_boolean:
  1521. newRow = JNIenv->NewBooleanArray(numElems);
  1522. JNIenv->SetBooleanArrayRegion((jbooleanArray) newRow, 0, numElems, (jboolean *) data);
  1523. javaTypeSignature = "[Z";
  1524. break;
  1525. case type_int:
  1526. if (childType->fieldType & RFTMunsigned)
  1527. UNSUPPORTED("unsigned integers");
  1528. switch (childType->length)
  1529. {
  1530. case 1:
  1531. newRow = JNIenv->NewByteArray(numElems);
  1532. JNIenv->SetByteArrayRegion((jbyteArray) newRow, 0, numElems, (jbyte *) data);
  1533. javaTypeSignature = "[B";
  1534. break;
  1535. case 2:
  1536. newRow = JNIenv->NewShortArray(numElems);
  1537. JNIenv->SetShortArrayRegion((jshortArray) newRow, 0, numElems, (jshort *) data);
  1538. javaTypeSignature = "[S";
  1539. break;
  1540. case 4:
  1541. newRow = JNIenv->NewIntArray(numElems);
  1542. JNIenv->SetIntArrayRegion((jintArray) newRow, 0, numElems, (jint *) data);
  1543. javaTypeSignature = "[I";
  1544. break;
  1545. case 8:
  1546. newRow = JNIenv->NewLongArray(numElems);
  1547. JNIenv->SetLongArrayRegion((jlongArray) newRow, 0, numElems, (jlong *) data);
  1548. javaTypeSignature = "[J";
  1549. break;
  1550. default:
  1551. UNSUPPORTED("non-standard integer sizes");
  1552. break;
  1553. }
  1554. break;
  1555. case type_real:
  1556. switch (childType->length)
  1557. {
  1558. case 4:
  1559. newRow = JNIenv->NewFloatArray(numElems);
  1560. JNIenv->SetFloatArrayRegion((jfloatArray) newRow, 0, numElems, (float *) data);
  1561. javaTypeSignature = "[F";
  1562. break;
  1563. case 8:
  1564. newRow = JNIenv->NewDoubleArray(numElems);
  1565. JNIenv->SetDoubleArrayRegion((jdoubleArray) newRow, 0, numElems, (double *) data);
  1566. javaTypeSignature = "[D";
  1567. break;
  1568. default:
  1569. throwUnexpected();
  1570. break;
  1571. }
  1572. break;
  1573. case type_string:
  1574. case type_varstring:
  1575. case type_unicode:
  1576. case type_utf8:
  1577. newRow = JNIenv->NewObjectArray(numElems, langStringClass, NULL);
  1578. javaTypeSignature = "[Ljava/lang/String;";
  1579. processElements = true;
  1580. break;
  1581. case type_data:
  1582. newRow = JNIenv->NewObjectArray(numElems, JNIenv->FindClass("[B"), NULL);
  1583. javaTypeSignature = "[[B";
  1584. processElements = true;
  1585. break;
  1586. default:
  1587. throwUnexpected();
  1588. }
  1589. jfieldID fieldId = getFieldId(field, javaTypeSignature, "Array");
  1590. JNIenv->SetObjectField(row, fieldId, newRow);
  1591. row = newRow;
  1592. inSet = true;
  1593. return processElements;
  1594. }
  1595. virtual bool processBeginDataset(const RtlFieldInfo * field, unsigned numRows)
  1596. {
  1597. push();
  1598. idxStack.append(idx);
  1599. idx = 0;
  1600. inDataSet = true;
  1601. // Create an empty array
  1602. jfieldID childId = getFieldId( field, NULL, "RECORD");
  1603. jobject newRow = NULL;
  1604. if (numRows)
  1605. {
  1606. jclass arrayClass = getClassForChild(childId);
  1607. jmethodID isArrayMethod = JNIenv->GetMethodID(JNIenv->GetObjectClass(arrayClass), "isArray", "()Z" );
  1608. if (!JNIenv->CallBooleanMethod(arrayClass, isArrayMethod))
  1609. {
  1610. JNIenv->ExceptionClear();
  1611. VStringBuffer message("javaembed: Array expected for field %s", field->name);
  1612. rtlFail(0, message.str());
  1613. }
  1614. // Set up constructor etc for the child rows, so we don't do it per row
  1615. jmethodID getTypeMethod = JNIenv->GetMethodID(JNIenv->GetObjectClass(arrayClass), "getComponentType", "()Ljava/lang/Class;" );
  1616. Class = (jclass) JNIenv->CallObjectMethod(arrayClass, getTypeMethod);
  1617. setConstructor();
  1618. // Now we need to create the array
  1619. newRow = JNIenv->NewObjectArray(numRows, Class, NULL);
  1620. }
  1621. JNIenv->SetObjectField(row, childId, newRow);
  1622. row = newRow;
  1623. return true;
  1624. }
  1625. virtual bool processBeginRow(const RtlFieldInfo * field)
  1626. {
  1627. if (field == outerRow)
  1628. row = JNIenv->NewObject(Class, constructor);
  1629. else
  1630. {
  1631. push();
  1632. stack.append(constructor);
  1633. // Now we have to create the child object
  1634. jobject newRow = NULL;
  1635. if (inDataSet)
  1636. {
  1637. newRow = JNIenv->NewObject(Class, constructor);
  1638. JNIenv->SetObjectArrayElement((jobjectArray) row, idx++, newRow);
  1639. }
  1640. else
  1641. {
  1642. // All this is done once per dataset in the nested dataset case. But for embedded record case we have to do it here
  1643. jfieldID childId = getFieldId( field, NULL, "RECORD");
  1644. Class = getClassForChild(childId);
  1645. setConstructor();
  1646. newRow = JNIenv->NewObject(Class, constructor);
  1647. JNIenv->SetObjectField(row, childId, newRow);
  1648. }
  1649. row = newRow;
  1650. }
  1651. return true;
  1652. }
  1653. virtual void processEndSet(const RtlFieldInfo * field)
  1654. {
  1655. JNIenv->DeleteLocalRef(row);
  1656. pop();
  1657. inSet = false;
  1658. }
  1659. virtual void processEndDataset(const RtlFieldInfo * field)
  1660. {
  1661. inDataSet = false;
  1662. idx = idxStack.popGet();
  1663. pop();
  1664. }
  1665. virtual void processEndRow(const RtlFieldInfo * field)
  1666. {
  1667. if (field != outerRow)
  1668. {
  1669. constructor = (jmethodID) stack.popGet();
  1670. JNIenv->DeleteLocalRef(row);
  1671. pop();
  1672. }
  1673. }
  1674. inline jobject getObject()
  1675. {
  1676. return row;
  1677. }
  1678. protected:
  1679. jclass getClassForChild(jfieldID childId)
  1680. {
  1681. jobject reflectedField = JNIenv->ToReflectedField(Class, childId, false);
  1682. jclass fieldClass =JNIenv->GetObjectClass(reflectedField);
  1683. jmethodID getTypeMethod = JNIenv->GetMethodID(fieldClass, "getType", "()Ljava/lang/Class;" );
  1684. jclass result = (jclass) JNIenv->CallObjectMethod(reflectedField, getTypeMethod);
  1685. JNIenv->DeleteLocalRef(reflectedField);
  1686. JNIenv->DeleteLocalRef(fieldClass);
  1687. return result;
  1688. }
  1689. void setConstructor()
  1690. {
  1691. constructor = JNIenv->GetMethodID(Class, "<init>", "()V");
  1692. if (!constructor)
  1693. {
  1694. JNIenv->ExceptionClear();
  1695. jmethodID getNameMethod = JNIenv->GetMethodID(JNIenv->GetObjectClass(Class), "getName", "()Ljava/lang/String;" );
  1696. jstring name = (jstring) JNIenv->CallObjectMethod(Class, getNameMethod);
  1697. const char *nameText = JNIenv->GetStringUTFChars(name, NULL);
  1698. VStringBuffer message("javaembed: no suitable constructor for class %s", nameText);
  1699. JNIenv->ReleaseStringUTFChars(name, nameText);
  1700. rtlFail(0, message.str());
  1701. }
  1702. }
  1703. jmethodID constructor;
  1704. };
  1705. //----------------------------------------------------------------------
  1706. // Wrap an IRowStream into a Java Iterator
  1707. class ECLDatasetIterator : public CInterfaceOf<IInterface>
  1708. {
  1709. public:
  1710. ECLDatasetIterator(CheckedJNIEnv *JNIenv, const RtlTypeInfo *_typeInfo, jclass className, IRowStream * _val)
  1711. : typeInfo(_typeInfo), val(_val),
  1712. dummyField("<row>", NULL, typeInfo),
  1713. javaBuilder(JNIenv, &dummyField, className)
  1714. {
  1715. nextRead = false;
  1716. nextPending = NULL;
  1717. }
  1718. bool hasNext()
  1719. {
  1720. if (!nextRead)
  1721. {
  1722. nextPending = (const byte *) val->ungroupedNextRow();
  1723. nextRead = true;
  1724. if (!nextPending)
  1725. val->stop();
  1726. }
  1727. return nextPending != NULL;
  1728. }
  1729. jobject next()
  1730. {
  1731. if (!hasNext())
  1732. return NULL;
  1733. typeInfo->process(nextPending, nextPending, &dummyField, javaBuilder); // Creates a java object from the incoming ECL row
  1734. nextRead = false;
  1735. return javaBuilder.getObject();
  1736. }
  1737. protected:
  1738. const RtlTypeInfo *typeInfo; // Not linked (or linkable)
  1739. Linked<IRowStream> val;
  1740. RtlFieldStrInfo dummyField;
  1741. JavaObjectBuilder javaBuilder;
  1742. const byte *nextPending;
  1743. bool nextRead;
  1744. };
  1745. //-------------------------------------------
  1746. // A Java function that returns a dataset will return a JavaRowStream object that can be
  1747. // interrogated to return each row of the result in turn
  1748. class JavaLocalFrame
  1749. {
  1750. public:
  1751. JavaLocalFrame(CheckedJNIEnv *_JNIenv, unsigned size = 16) : JNIenv(_JNIenv)
  1752. {
  1753. JNIenv->PushLocalFrame(size);
  1754. }
  1755. ~JavaLocalFrame()
  1756. {
  1757. JNIenv->PopLocalFrame(NULL);
  1758. }
  1759. private:
  1760. CheckedJNIEnv *JNIenv;
  1761. };
  1762. class JavaRowStream : public CInterfaceOf<IRowStream>
  1763. {
  1764. public:
  1765. JavaRowStream(jobject _iterator, IEngineRowAllocator *_resultAllocator)
  1766. : resultAllocator(_resultAllocator)
  1767. {
  1768. iterator = queryJNIEnv()->NewGlobalRef(_iterator, "iterator");
  1769. // Note that we can't cache the JNIEnv, iterClass, or methodIds here - calls may be made on different threads (though not at the same time).
  1770. }
  1771. ~JavaRowStream()
  1772. {
  1773. stop();
  1774. }
  1775. virtual const void *nextRow()
  1776. {
  1777. if (!iterator)
  1778. return NULL;
  1779. CheckedJNIEnv *JNIenv = queryJNIEnv();
  1780. JavaLocalFrame lf(JNIenv);
  1781. // Java code would be
  1782. // if (!iterator.hasNext)
  1783. // {
  1784. // stop();
  1785. // return NULL;
  1786. // }
  1787. // result = iterator.next();
  1788. jclass iterClass =JNIenv->GetObjectClass(iterator);
  1789. jmethodID hasNextMethod = JNIenv->GetMethodID(iterClass, "hasNext", "()Z" );
  1790. jboolean hasNext = JNIenv->CallBooleanMethod(iterator, hasNextMethod);
  1791. if (!hasNext)
  1792. {
  1793. stop();
  1794. return NULL;
  1795. }
  1796. jmethodID nextMethod = JNIenv->GetMethodID(iterClass, "next", "()Ljava/lang/Object;" );
  1797. jobject result = JNIenv->CallObjectMethod(iterator, nextMethod);
  1798. RtlDynamicRowBuilder rowBuilder(resultAllocator);
  1799. const RtlTypeInfo *typeInfo = resultAllocator->queryOutputMeta()->queryTypeInfo();
  1800. assertex(typeInfo);
  1801. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  1802. JavaRowBuilder javaRowBuilder(queryJNIEnv(), &dummyField, result);
  1803. size32_t len = typeInfo->build(rowBuilder, 0, &dummyField, javaRowBuilder);
  1804. return rowBuilder.finalizeRowClear(len);
  1805. }
  1806. virtual void stop()
  1807. {
  1808. resultAllocator.clear();
  1809. CheckedJNIEnv *JNIenv = queryJNIEnv();
  1810. if (JNIenv)
  1811. {
  1812. if (iterator)
  1813. {
  1814. JNIenv->DeleteGlobalRef(iterator);
  1815. iterator = NULL;
  1816. }
  1817. }
  1818. }
  1819. protected:
  1820. Linked<IEngineRowAllocator> resultAllocator;
  1821. jobject iterator;
  1822. };
  1823. const char *esdl2JavaSig(IEsdlDefinition &esdl, const char *esdlType)
  1824. {
  1825. EsdlBasicElementType t = esdl.translateSimpleType(esdlType);
  1826. switch (t)
  1827. {
  1828. case ESDLT_INT16:
  1829. case ESDLT_UINT16:
  1830. return "Ljava/lang/Short;";
  1831. case ESDLT_INT32:
  1832. case ESDLT_UINT32:
  1833. return "Ljava/lang/Integer;";
  1834. case ESDLT_INT64:
  1835. case ESDLT_UINT64:
  1836. return "Ljava/math/BigInteger;";
  1837. case ESDLT_BOOL:
  1838. return "Ljava/lang/Boolean;";
  1839. case ESDLT_FLOAT:
  1840. return "Ljava/lang/Float;";
  1841. case ESDLT_DOUBLE:
  1842. return "Ljava/lang/Double;";
  1843. case ESDLT_INT8:
  1844. case ESDLT_UINT8:
  1845. case ESDLT_BYTE:
  1846. case ESDLT_UBYTE:
  1847. return "Ljava/lang/Byte;";
  1848. case ESDLT_STRING:
  1849. return "Ljava/lang/String;";
  1850. case ESDLT_UNKOWN:
  1851. case ESDLT_STRUCT:
  1852. case ESDLT_REQUEST:
  1853. case ESDLT_RESPONSE:
  1854. case ESDLT_COMPLEX:
  1855. default:
  1856. return NULL;
  1857. }
  1858. }
  1859. const char *esdl2JavaFullClassName(IEsdlDefinition &esdl, const char *esdlType)
  1860. {
  1861. EsdlBasicElementType t = esdl.translateSimpleType(esdlType);
  1862. switch (t)
  1863. {
  1864. case ESDLT_INT16:
  1865. case ESDLT_UINT16:
  1866. return "java/lang/Short";
  1867. case ESDLT_INT32:
  1868. case ESDLT_UINT32:
  1869. return "java/lang/Integer";
  1870. case ESDLT_INT64:
  1871. case ESDLT_UINT64:
  1872. return "java/math/BigInteger";
  1873. case ESDLT_BOOL:
  1874. return "java/lang/Boolean";
  1875. case ESDLT_FLOAT:
  1876. return "java/lang/Float";
  1877. case ESDLT_DOUBLE:
  1878. return "java/lang/Double";
  1879. case ESDLT_INT8:
  1880. case ESDLT_UINT8:
  1881. case ESDLT_BYTE:
  1882. case ESDLT_UBYTE:
  1883. return "java/lang/Byte";
  1884. case ESDLT_STRING:
  1885. return "java/lang/String";
  1886. case ESDLT_UNKOWN:
  1887. case ESDLT_STRUCT:
  1888. case ESDLT_REQUEST:
  1889. case ESDLT_RESPONSE:
  1890. case ESDLT_COMPLEX:
  1891. default:
  1892. return NULL;
  1893. }
  1894. }
  1895. class JavaObjectXmlWriter : public CInterface
  1896. {
  1897. public:
  1898. JavaObjectXmlWriter(CheckedJNIEnv *_JNIenv, jobject _obj, const char *_reqType, IEsdlDefinition &_esdl, const char *_esdlService, IXmlWriter &_writer)
  1899. : JNIenv(_JNIenv), obj(_obj), writer(_writer), esdl(_esdl), esdlService(_esdlService), reqType(_reqType)
  1900. {
  1901. Class = (jclass) JNIenv->NewGlobalRef(JNIenv->GetObjectClass(obj), "class");
  1902. }
  1903. ~JavaObjectXmlWriter()
  1904. {
  1905. if (Class)
  1906. JNIenv->DeleteGlobalRef(Class);
  1907. HashIterator it(javaClasses);
  1908. ForEach(it)
  1909. {
  1910. IMapping &entry = it.query();
  1911. jclass *pClass = javaClasses.mapToValue(&entry);
  1912. if (pClass)
  1913. JNIenv->DeleteGlobalRef(*pClass);
  1914. }
  1915. }
  1916. void writeSimpleType(const char *fieldname, jobject fieldObj)
  1917. {
  1918. jstring fieldStr = (jstring) JNIenv->CallObjectMethod(fieldObj, object_toString);
  1919. if (!fieldStr)
  1920. return;
  1921. const char *text = JNIenv->GetStringUTFChars(fieldStr, NULL);
  1922. if (text)
  1923. writer.outputCString(text, fieldname);
  1924. JNIenv->ReleaseStringUTFChars(fieldStr, text);
  1925. JNIenv->DeleteLocalRef(fieldStr);
  1926. }
  1927. void writeSimpleType(jclass parentClass, jobject parentObject, const char *fieldname, const char *javaSig)
  1928. {
  1929. if (!fieldname || !*fieldname)
  1930. return;
  1931. if (!javaSig || !*javaSig)
  1932. return;
  1933. jfieldID fieldId = JNIenv->GetFieldID(parentClass, fieldname, javaSig);
  1934. if (!fieldId)
  1935. return;
  1936. jobject fieldObj = (jobject) JNIenv->GetObjectField(parentObject, fieldId);
  1937. if (!fieldObj)
  1938. return;
  1939. writeSimpleType(fieldname, fieldObj);
  1940. JNIenv->DeleteLocalRef(fieldObj);
  1941. }
  1942. void writeSimpleType(jclass parentClass, jobject parentObject, IEsdlDefObject &defObject)
  1943. {
  1944. const char *fieldname = defObject.queryName();
  1945. const char *javaSig = esdl2JavaSig(esdl, defObject.queryProp("type"));
  1946. writeSimpleType(parentClass, parentObject, fieldname, javaSig);
  1947. }
  1948. void writeEnumType(jclass parentClass, jobject parentObject, IEsdlDefObject &defObject)
  1949. {
  1950. const char *fieldname = defObject.queryName();
  1951. VStringBuffer javaSig("L%s/%s;", esdlService.str(), defObject.queryProp("enum_type"));
  1952. jfieldID fieldId = JNIenv->GetFieldID(parentClass, fieldname, javaSig);
  1953. if (!fieldId)
  1954. return;
  1955. jobject fieldObj = (jobject) JNIenv->GetObjectField(parentObject, fieldId);
  1956. if (!fieldObj)
  1957. return;
  1958. jstring fieldStr = (jstring) JNIenv->CallObjectMethod(fieldObj, object_toString);
  1959. const char *text = JNIenv->GetStringUTFChars(fieldStr, NULL);
  1960. if (text)
  1961. writer.outputCString(text, defObject.queryName());
  1962. JNIenv->ReleaseStringUTFChars(fieldStr, text);
  1963. }
  1964. void writeComplexType(jclass parentClass, jobject parentObject, IEsdlDefObject &defObject)
  1965. {
  1966. IEsdlDefStruct *defStruct = esdl.queryStruct(defObject.queryProp("complex_type"));
  1967. if (!defStruct)
  1968. return;
  1969. const char *fieldname = defObject.queryName();
  1970. VStringBuffer javaSig("L%s/%s;", esdlService.str(), defObject.queryProp("complex_type"));
  1971. jfieldID fieldId = JNIenv->GetFieldID(parentClass, fieldname, javaSig); //tbd cache this
  1972. if (!fieldId)
  1973. return;
  1974. jobject fieldObj = (jobject) JNIenv->GetObjectField(parentObject, fieldId);
  1975. if (!fieldObj)
  1976. return;
  1977. writer.outputBeginNested(fieldname, true);
  1978. writeChildren(JNIenv->GetObjectClass(fieldObj), fieldObj, defStruct);
  1979. writer.outputEndNested(fieldname);
  1980. }
  1981. void writeSimpleArray(jobjectArray arrayObj, jint count, const char *name, const char *item_tag)
  1982. {
  1983. writer.outputBeginNested(name, true);
  1984. writer.outputBeginArray(item_tag);
  1985. for (jint i=0; i < count; i++)
  1986. {
  1987. jobject elementObj = JNIenv->GetObjectArrayElement(arrayObj, i);
  1988. writeSimpleType(item_tag, elementObj);
  1989. JNIenv->DeleteLocalRef(elementObj);
  1990. }
  1991. writer.outputEndArray(item_tag);
  1992. writer.outputEndNested(name);
  1993. }
  1994. void writeComplexArray(jobjectArray arrayObj, jint count, const char *name, const char *item_tag, const char *itemTypeName)
  1995. {
  1996. writer.outputBeginNested(name, true);
  1997. writer.outputBeginArray(item_tag);
  1998. {
  1999. VStringBuffer javaClassName("%s/%s", esdlService.str(), itemTypeName);
  2000. jclass elementClass = FindClass(javaClassName);
  2001. if (!elementClass)
  2002. return;
  2003. IEsdlDefStruct *defStruct = esdl.queryStruct(itemTypeName);
  2004. if (!defStruct)
  2005. return;
  2006. for (jint i=0; i < count; i++)
  2007. {
  2008. jobject elementObj = JNIenv->GetObjectArrayElement(arrayObj, i);
  2009. writer.outputBeginNested(item_tag, true);
  2010. writeChildren(elementClass, elementObj, defStruct);
  2011. writer.outputEndNested(item_tag);
  2012. JNIenv->DeleteLocalRef(elementObj);
  2013. }
  2014. }
  2015. writer.outputEndArray(item_tag);
  2016. writer.outputEndNested(name);
  2017. }
  2018. void writeArray(jclass parentClass, jobject parentObject, IEsdlDefObject &defObject)
  2019. {
  2020. const char *itemTypeName = defObject.queryProp("type");
  2021. if (!itemTypeName)
  2022. return;
  2023. const char *item_tag = defObject.queryProp("item_tag");
  2024. if (!item_tag)
  2025. return;
  2026. const char *fieldname = defObject.queryName();
  2027. jfieldID fieldId = JNIenv->GetFieldID(parentClass, fieldname, "Ljava/util/ArrayList;");
  2028. if (!fieldId)
  2029. return;
  2030. jobject arrayListObj = (jobject) JNIenv->GetObjectField(parentObject, fieldId);
  2031. if (!arrayListObj)
  2032. return;
  2033. jobjectArray arrayObj = (jobjectArray) JNIenv->CallObjectMethod(arrayListObj, arrayList_toArray);
  2034. if (arrayObj)
  2035. {
  2036. jint count = JNIenv->GetArrayLength(arrayObj);
  2037. if (count)
  2038. {
  2039. if (esdl2JavaSig(esdl, itemTypeName))
  2040. writeSimpleArray(arrayObj, count, defObject.queryName(), item_tag);
  2041. else
  2042. writeComplexArray(arrayObj, count, defObject.queryName(), item_tag, itemTypeName);
  2043. }
  2044. JNIenv->DeleteLocalRef(arrayObj);
  2045. }
  2046. JNIenv->DeleteLocalRef(arrayListObj);
  2047. }
  2048. void writeChildren(jclass javaClass, jobject javaObject, IEsdlDefStruct *defStruct)
  2049. {
  2050. Owned<IEsdlDefObjectIterator> children = defStruct->getChildren();
  2051. ForEach (*children)
  2052. {
  2053. IEsdlDefObject &child = children->query();
  2054. if (child.getEsdlType()==EsdlTypeElement)
  2055. {
  2056. if (child.hasProp("type"))
  2057. writeSimpleType(javaClass, javaObject, child);
  2058. else if (child.hasProp("complex_type"))
  2059. writeComplexType(javaClass, javaObject, child);
  2060. }
  2061. else if (child.getEsdlType()==EsdlTypeEnumRef)
  2062. {
  2063. writeEnumType(javaClass, javaObject, child);
  2064. }
  2065. else if (child.getEsdlType()==EsdlTypeArray)
  2066. {
  2067. writeArray(javaClass, javaObject, child);
  2068. }
  2069. }
  2070. }
  2071. void write()
  2072. {
  2073. IEsdlDefStruct *reqStruct = esdl.queryStruct(reqType);
  2074. const char *name = reqStruct->queryName();
  2075. writer.outputBeginNested("Response", true);
  2076. writer.outputBeginNested("Results", true);
  2077. writer.outputBeginNested("Result", true);
  2078. writer.outputBeginDataset(name, true);
  2079. writer.outputBeginArray("Row");
  2080. writer.outputBeginNested("Row", true);
  2081. writeChildren(Class, obj, reqStruct);
  2082. writer.outputEndNested("Row");
  2083. writer.outputEndArray("Row");
  2084. writer.outputEndDataset(name);
  2085. writer.outputEndNested("Result");
  2086. writer.outputEndNested("Results");
  2087. writer.outputEndNested("Response");
  2088. }
  2089. jclass FindClass(const char *name)
  2090. {
  2091. jclass *pClass = javaClasses.getValue(name);
  2092. if (pClass)
  2093. return *pClass;
  2094. jclass localClass = JNIenv->FindClass(name);
  2095. if (!localClass)
  2096. return 0;
  2097. jclass Class = (jclass) JNIenv->NewGlobalRef(localClass, "class");
  2098. javaClasses.setValue(name, Class);
  2099. JNIenv->DeleteLocalRef(localClass);
  2100. return Class;
  2101. }
  2102. CheckedJNIEnv *JNIenv;
  2103. MapStringTo<jclass> javaClasses;
  2104. jclass Class;
  2105. jobject obj;
  2106. IXmlWriter &writer;
  2107. IEsdlDefinition &esdl;
  2108. StringAttr reqType;
  2109. StringAttr esdlService;
  2110. };
  2111. //-------------------------------------------
  2112. // There is a singleton JavaThreadContext per thread. This handles the interaction between
  2113. // the C++ thread and the java threading library, ensuring that we register/unregister as needed,
  2114. // and that any thread_local function contexts are destroyed before we detach from the java thread
  2115. class JavaThreadContext
  2116. {
  2117. public:
  2118. CheckedJNIEnv *JNIenv; /* receives pointer to native method interface */
  2119. public:
  2120. JavaThreadContext()
  2121. {
  2122. jint res = globalState->javaVM->AttachCurrentThread((void **) &JNIenv, NULL);
  2123. assertex(res >= 0);
  2124. setThreadClassLoader(getSystemClassLoader());
  2125. }
  2126. ~JavaThreadContext()
  2127. {
  2128. // Make sure all thread-local function contexts are destroyed before we detach from
  2129. // the Java thread
  2130. contexts.kill();
  2131. // According to the Java VM 1.7 docs, "A native thread attached to
  2132. // the VM must call DetachCurrentThread() to detach itself before
  2133. // exiting."
  2134. globalState->javaVM->DetachCurrentThread();
  2135. }
  2136. jobject getSystemClassLoader()
  2137. {
  2138. jobject systemClassLoaderObj = JNIenv->CallStaticObjectMethod(javaLangClassLoaderClass, cl_getSystemClassLoader);
  2139. assertex(systemClassLoaderObj);
  2140. return systemClassLoaderObj;
  2141. }
  2142. void setThreadClassLoader(jobject classLoader)
  2143. {
  2144. jobject threadObj = JNIenv->CallStaticObjectMethod(javaLangThreadClass, thread_currentThread);
  2145. JNIenv->CallObjectMethod(threadObj, thread_setContextClassLoader, classLoader);
  2146. }
  2147. jobject getThreadClassLoader()
  2148. {
  2149. JNIenv->ExceptionClear();
  2150. jobject threadObj = JNIenv->CallStaticObjectMethod(javaLangThreadClass, thread_currentThread);
  2151. jobject contextClassLoaderObj = JNIenv->CallObjectMethod(threadObj, thread_getContextClassLoader);
  2152. assertex(contextClassLoaderObj);
  2153. return contextClassLoaderObj;
  2154. }
  2155. void writeObjectResult(jobject result, IEsdlDefinition *esdl, const char *esdlservice, const char *name, IXmlWriter *writer)
  2156. {
  2157. JavaObjectXmlWriter x(JNIenv, result, name, *esdl, esdlservice, *writer);
  2158. x.write();
  2159. }
  2160. void registerContext(IEmbedFunctionContext *ctx)
  2161. {
  2162. // Note - this object is thread-local so no need for a critsec
  2163. contexts.append(*ctx);
  2164. }
  2165. private:
  2166. IArrayOf<IEmbedFunctionContext> contexts;
  2167. };
  2168. class JavaXmlBuilder : implements IXmlWriterExt, public CInterface
  2169. {
  2170. public:
  2171. IMPLEMENT_IINTERFACE;
  2172. JavaXmlBuilder(CheckedJNIEnv *_JNIenv, IEsdlDefinition *esdl_, const char *esdlservice, const char *esdltype_)
  2173. : JNIenv(_JNIenv), esdl(esdl_), javaPackage(esdlservice), esdlType(esdltype_)
  2174. {
  2175. }
  2176. ~JavaXmlBuilder()
  2177. {
  2178. while (defStack.length())
  2179. popDefStackEntry(JNIenv);
  2180. HashIterator it(javaClasses);
  2181. ForEach(it)
  2182. {
  2183. IMapping &entry = it.query();
  2184. jclass *pClass = javaClasses.mapToValue(&entry);
  2185. if (pClass)
  2186. JNIenv->DeleteGlobalRef(*pClass);
  2187. }
  2188. }
  2189. void initWriter()
  2190. {
  2191. }
  2192. IXmlWriterExt & clear()
  2193. {
  2194. throwUnexpected();
  2195. }
  2196. virtual size32_t length() const
  2197. {
  2198. return 0;
  2199. }
  2200. virtual const char *str() const
  2201. {
  2202. throwUnexpected();
  2203. }
  2204. virtual void finalize() override
  2205. {
  2206. }
  2207. virtual IInterface *saveLocation() const {return nullptr;}
  2208. virtual void rewindTo(IInterface *loc)
  2209. {
  2210. //needs to be a no-op because it is used, but the way its used to trim empty xml sections I think we're fairly safe.
  2211. //revisit cleaning up any empty objects later.
  2212. }
  2213. inline IEsdlDefStruct *queryCurrentEsdlStruct()
  2214. {
  2215. if (!defStack.length() || !defStack.tos().defType)
  2216. return NULL;
  2217. return dynamic_cast<IEsdlDefStruct*>(defStack.tos().defType.get());
  2218. }
  2219. inline jobject getObject()
  2220. {
  2221. if (!defStack.length())
  2222. return 0;
  2223. return defStack.item(0).obj;
  2224. }
  2225. inline jobject getCurJavaObject()
  2226. {
  2227. if (!defStack.length())
  2228. return 0;
  2229. return defStack.tos().obj;
  2230. }
  2231. inline jclass getCurJavaClass()
  2232. {
  2233. if (!defStack.length())
  2234. return 0;
  2235. return defStack.tos().Class;
  2236. }
  2237. inline jmethodID getCurJavaConstructor()
  2238. {
  2239. if (!defStack.length())
  2240. return 0;
  2241. return defStack.tos().constructor;
  2242. }
  2243. virtual void outputEnumString(unsigned size, const char *text, const char *fieldname, IEsdlDefObject *defField)
  2244. {
  2245. const char *enum_type = defField->queryProp("enum_type");
  2246. if (!enum_type || !*enum_type)
  2247. return;
  2248. VStringBuffer enumClassName("%s/%s", javaPackage.str(), enum_type);
  2249. VStringBuffer enumSig("L%s;", enumClassName.str());
  2250. jfieldID fieldId = JNIenv->GetFieldID(getCurJavaClass(), fieldname, enumSig);
  2251. if (!fieldId)
  2252. return;
  2253. jclass enumClass = FindClass(enumClassName);
  2254. jmethodID fromString = JNIenv->GetStaticMethodID(enumClass, "fromString", "(Ljava/lang/String;)LEsdlExample/AddressType;"); //All types currently used for ESDL mapping have string constructors
  2255. StringAttr s(text, size);
  2256. jstring strvalue = JNIenv->NewStringUTF(s);
  2257. jobject value = JNIenv->CallStaticObjectMethod(enumClass, fromString, strvalue);
  2258. JNIenv->DeleteLocalRef(strvalue);
  2259. JNIenv->SetObjectField(getCurJavaObject(), fieldId, value);
  2260. JNIenv->DeleteLocalRef(value);
  2261. }
  2262. virtual void outputString(unsigned size, const char *text, const char *fieldname)
  2263. {
  2264. DefStackEntry *parent = defStack.length() ? &defStack.tos() : NULL;
  2265. if (!parent)
  2266. return;
  2267. const char *defTypeName = NULL;
  2268. bool isArray = (parent->defObj && parent->defObj->getEsdlType()==EsdlTypeArray);
  2269. if (isArray)
  2270. defTypeName = parent->defObj->queryProp("type");
  2271. else
  2272. {
  2273. IEsdlDefStruct *defStruct = queryCurrentEsdlStruct();
  2274. if (!defStruct)
  2275. return;
  2276. IEsdlDefObject *defField = defStruct->queryChild(fieldname);
  2277. if (!defField)
  2278. return;
  2279. if (defField->getEsdlType()==EsdlTypeEnumRef)
  2280. return outputEnumString(size, text, fieldname, defField);
  2281. defTypeName = defField->queryProp("type");
  2282. }
  2283. if (!defTypeName)
  2284. return;
  2285. const char *javaSig = esdl2JavaSig(*esdl, defTypeName);
  2286. if (!javaSig)
  2287. return;
  2288. const char *fieldClassName = esdl2JavaFullClassName(*esdl, defTypeName);
  2289. jclass typeClass = FindClass(fieldClassName);
  2290. jmethodID typeStringConstructor = JNIenv->GetMethodID(typeClass, "<init>", "(Ljava/lang/String;)V"); //All types currently used for ESDL mapping have string constructors
  2291. StringAttr s(text, size);
  2292. jstring strvalue = JNIenv->NewStringUTF(s);
  2293. jobject value = JNIenv->NewObject(typeClass, typeStringConstructor, strvalue);
  2294. JNIenv->DeleteLocalRef(strvalue);
  2295. if (!value)
  2296. return;
  2297. if (isArray)
  2298. JNIenv->CallObjectMethod(parent->obj, parent->append, value);
  2299. else
  2300. {
  2301. jfieldID fieldId = JNIenv->GetFieldID(getCurJavaClass(), fieldname, javaSig);
  2302. if (fieldId)
  2303. JNIenv->SetObjectField(getCurJavaObject(), fieldId, value);
  2304. }
  2305. JNIenv->DeleteLocalRef(value);
  2306. }
  2307. void outputString(const char *text, const char *fieldname)
  2308. {
  2309. outputString((unsigned)strlen(text), text, fieldname);
  2310. }
  2311. virtual void outputNumericString(const char *field, const char *fieldname)
  2312. {
  2313. outputString(field, fieldname);
  2314. }
  2315. virtual void outputBool(bool value, const char *fieldname)
  2316. {
  2317. outputString(value ? "true" : "false", fieldname);
  2318. }
  2319. virtual void outputUInt(unsigned __int64 field, unsigned size, const char *fieldname)
  2320. {
  2321. StringBuffer value;
  2322. value.append(field);
  2323. outputString(value.length(), value, fieldname);
  2324. }
  2325. virtual void outputInt(__int64 field, unsigned size, const char *fieldname)
  2326. {
  2327. StringBuffer value;
  2328. value.append(field);
  2329. outputString(value.length(), value, fieldname);
  2330. }
  2331. virtual void outputReal(double field, const char *fieldname)
  2332. {
  2333. StringBuffer value;
  2334. value.append(field);
  2335. outputString(value.length(), value, fieldname);
  2336. }
  2337. virtual void outputDecimal(const void *field, unsigned size, unsigned precision, const char *fieldname)
  2338. {
  2339. Decimal d;
  2340. d.setDecimal(size, precision, field);
  2341. outputString(d.getCString(), fieldname);
  2342. }
  2343. virtual void outputUDecimal(const void *field, unsigned size, unsigned precision, const char *fieldname)
  2344. {
  2345. Decimal d;
  2346. d.setUDecimal(size, precision, field);
  2347. outputString(d.getCString(), fieldname);
  2348. }
  2349. virtual void outputQString(unsigned len, const char *field, const char *fieldname)
  2350. {
  2351. MemoryAttr tempBuffer;
  2352. char * temp;
  2353. if (len <= 100)
  2354. temp = (char *)alloca(len);
  2355. else
  2356. temp = (char *)tempBuffer.allocate(len);
  2357. rtlQStrToStr(len, temp, len, field);
  2358. outputString(len, temp, fieldname);
  2359. }
  2360. virtual void outputUnicode(unsigned len, const UChar *field, const char *fieldname)
  2361. {
  2362. char * buff = 0;
  2363. unsigned bufflen = 0;
  2364. rtlUnicodeToCodepageX(bufflen, buff, len, field, "utf-8");
  2365. outputString(bufflen, buff, fieldname);
  2366. rtlFree(buff);
  2367. }
  2368. virtual void outputUtf8(unsigned len, const char *field, const char *fieldname)
  2369. {
  2370. outputString(len, field, fieldname);
  2371. }
  2372. virtual void outputData(unsigned len, const void *value, const char *fieldname)
  2373. {
  2374. }
  2375. virtual void outputQuoted(const char *text) //would have to let beginNested represent simple types with content set using this?
  2376. {
  2377. }
  2378. virtual void outputBeginDataset(const char *dsname, bool nestChildren) //not used by ESDL engine
  2379. {
  2380. }
  2381. virtual void outputEndDataset(const char *dsname)
  2382. {
  2383. }
  2384. inline IEsdlDefObject *queryChildStructDefObj(IEsdlDefObject *child)
  2385. {
  2386. if (child)
  2387. {
  2388. switch (child->getEsdlType())
  2389. {
  2390. case EsdlTypeArray:
  2391. {
  2392. const char *structType = child->queryProp("type");
  2393. if (structType)
  2394. return esdl->queryObj(structType);
  2395. break;
  2396. }
  2397. case EsdlTypeElement:
  2398. {
  2399. const char *structType = child->queryProp("complex_type");
  2400. if (structType)
  2401. return esdl->queryObj(structType);
  2402. break;
  2403. }
  2404. default:
  2405. break;
  2406. }
  2407. }
  2408. return NULL;
  2409. }
  2410. virtual void outputBeginNested(const char *fieldname, bool nestChildren)
  2411. {
  2412. IEsdlDefStruct *defStruct = NULL;
  2413. IEsdlDefObject *defField = NULL;
  2414. IEsdlDefObject *defType = NULL;
  2415. if (!defStack.length())
  2416. {
  2417. defType = esdl->queryObj(fieldname);
  2418. }
  2419. else
  2420. {
  2421. DefStackEntry &parent = defStack.tos();
  2422. if (parent.defObj && parent.defObj->getEsdlType()==EsdlTypeArray)
  2423. {
  2424. defType = parent.defType;
  2425. }
  2426. else
  2427. {
  2428. defStruct = queryCurrentEsdlStruct();
  2429. if (defStruct)
  2430. {
  2431. defField = defStruct->queryChild(fieldname);
  2432. if (defField)
  2433. defType = queryChildStructDefObj(defField);
  2434. }
  2435. }
  2436. }
  2437. pushDefStackEntry(JNIenv, javaPackage, fieldname, defType, defField);
  2438. }
  2439. virtual void outputEndNested(const char *fieldname)
  2440. {
  2441. if (defStack.length()<=1) //don't destroy root object yet
  2442. return;
  2443. if (!streq(fieldname, defStack.tos().name)) //should be exception? or forgive and forget?
  2444. return;
  2445. popDefStackEntry(JNIenv);
  2446. }
  2447. virtual void outputSetAll()
  2448. {
  2449. }
  2450. virtual void outputBeginArray(const char *fieldname)
  2451. {
  2452. }
  2453. virtual void outputEndArray(const char *fieldname)
  2454. {
  2455. }
  2456. virtual void outputInlineXml(const char *text)
  2457. {
  2458. }
  2459. virtual void outputXmlns(const char *name, const char *uri)
  2460. {
  2461. }
  2462. virtual void cutFrom(IInterface *location, StringBuffer& databuf)
  2463. {
  2464. }
  2465. virtual void outputInline(const char* text)
  2466. {
  2467. }
  2468. public:
  2469. CheckedJNIEnv *JNIenv;
  2470. Linked<IEsdlDefinition> esdl;
  2471. StringAttr javaPackage;
  2472. StringAttr esdlType;
  2473. class DefStackEntry : public CInterface
  2474. {
  2475. public:
  2476. DefStackEntry(const char *fieldname, IEsdlDefObject *_defType, IEsdlDefObject *_defObj) : name(fieldname), defType(_defType), defObj(_defObj), Class(0), obj(0), constructor(0), append(0), fieldId(0)
  2477. {
  2478. }
  2479. ~DefStackEntry()
  2480. {
  2481. }
  2482. public:
  2483. Linked<IEsdlDefObject> defType;
  2484. Linked<IEsdlDefObject> defObj;
  2485. StringAttr name;
  2486. jclass Class;
  2487. jmethodID constructor;
  2488. jmethodID append;
  2489. jfieldID fieldId;
  2490. jobject obj;
  2491. };
  2492. jobject MakeObjectGlobal(jobject local)
  2493. {
  2494. if (!local)
  2495. return 0;
  2496. jobject global = JNIenv->NewGlobalRef(local, "makeObjectGlobal");
  2497. JNIenv->DeleteLocalRef(local);
  2498. return global;
  2499. }
  2500. jclass FindClass(const char *name)
  2501. {
  2502. jclass *pClass = javaClasses.getValue(name);
  2503. if (pClass)
  2504. return *pClass;
  2505. jclass Class = (jclass) MakeObjectGlobal(JNIenv->FindClass(name));
  2506. javaClasses.setValue(name, Class); //even save if result has no class
  2507. return Class;
  2508. }
  2509. void popDefStackEntry(CheckedJNIEnv *JNIenv)
  2510. {
  2511. if (!defStack.length())
  2512. return;
  2513. Owned<DefStackEntry> entry = &defStack.popGet();
  2514. if (entry->obj)
  2515. JNIenv->DeleteGlobalRef(entry->obj);
  2516. }
  2517. void pushDefStackEntry(CheckedJNIEnv *JNIenv, const char *package, const char *fieldname, IEsdlDefObject *defType, IEsdlDefObject *defObject)
  2518. {
  2519. DefStackEntry *parent = defStack.length() ? &defStack.tos() : NULL;
  2520. Owned<DefStackEntry> entry = new DefStackEntry(fieldname, defType, defObject);
  2521. JNIenv->ExceptionClear();
  2522. if (defObject && defObject->getEsdlType()==EsdlTypeArray)
  2523. {
  2524. entry->Class = arrayListClass;
  2525. entry->constructor = arrayList_constructor;
  2526. entry->append = arrayList_add;
  2527. entry->obj = MakeObjectGlobal(JNIenv->NewObject(entry->Class, entry->constructor));
  2528. if (entry->obj)
  2529. {
  2530. if (parent && parent->Class)
  2531. {
  2532. entry->fieldId = JNIenv->GetFieldID(parent->Class, fieldname, "Ljava/util/ArrayList;");
  2533. if (parent->obj && entry->fieldId)
  2534. JNIenv->SetObjectField(parent->obj, entry->fieldId, entry->obj);
  2535. }
  2536. }
  2537. }
  2538. else if (defType)
  2539. {
  2540. VStringBuffer javaClassName("%s/%s", package, defType->queryName());
  2541. entry->Class = FindClass(javaClassName);
  2542. if (entry->Class)
  2543. {
  2544. entry->constructor = JNIenv->GetMethodID(entry->Class, "<init>", "()V");
  2545. entry->obj = MakeObjectGlobal(JNIenv->NewObject(entry->Class, entry->constructor));
  2546. if (entry->obj)
  2547. {
  2548. if (parent)
  2549. {
  2550. if (parent->defObj && parent->defObj->getEsdlType()==EsdlTypeArray)
  2551. JNIenv->CallObjectMethod(parent->obj, parent->append, entry->obj);
  2552. else if (parent->Class)
  2553. {
  2554. VStringBuffer javaSig("L%s;", javaClassName.str());
  2555. entry->fieldId = JNIenv->GetFieldID(parent->Class, fieldname, javaSig);
  2556. if (parent->obj && entry->fieldId)
  2557. JNIenv->SetObjectField(parent->obj, entry->fieldId, entry->obj);
  2558. }
  2559. }
  2560. }
  2561. }
  2562. }
  2563. defStack.append(*entry.getClear());
  2564. }
  2565. CIArrayOf<DefStackEntry> defStack;
  2566. MapStringTo<jclass> javaClasses;
  2567. };
  2568. // Each call to a Java function will use a new JavaEmbedScriptContext object
  2569. #define MAX_JNI_ARGS 10
  2570. class JavaClassReader
  2571. {
  2572. public:
  2573. JavaClassReader(const char *filename)
  2574. {
  2575. // Pull apart a class file to see its name and signature.
  2576. /* From https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.1
  2577. ClassFile {
  2578. u4 magic;
  2579. u2 minor_version;
  2580. u2 major_version;
  2581. u2 constant_pool_count;
  2582. cp_info constant_pool[constant_pool_count-1];
  2583. u2 access_flags;
  2584. u2 this_class;
  2585. u2 super_class;
  2586. u2 interfaces_count;
  2587. u2 interfaces[interfaces_count];
  2588. u2 fields_count;
  2589. field_info fields[fields_count];
  2590. u2 methods_count;
  2591. method_info methods[methods_count];
  2592. u2 attributes_count;
  2593. attribute_info attributes[attributes_count];
  2594. }
  2595. */
  2596. #ifdef TRACE_CLASSFILE
  2597. DBGLOG("Reading class file created in %s", filename);
  2598. #endif
  2599. Owned<IFile> file = createIFile(filename);
  2600. OwnedIFileIO io = file->open(IFOread);
  2601. assertex(io);
  2602. read(io, 0, (size32_t)-1, b);
  2603. b.setEndian(__BIG_ENDIAN);
  2604. uint32_t magic;
  2605. b.read(magic);
  2606. if (magic != 0xcafebabe)
  2607. throwUnexpected();
  2608. uint16_t major, minor, cpc;
  2609. b.read(major);
  2610. b.read(minor);
  2611. b.read(cpc);
  2612. constOffsets = new unsigned[cpc];
  2613. constOffsets[0] = 0;
  2614. for (int i = 0; i < cpc-1; i++) // There are only cpc-1 entries, for reasons best known to the java designers
  2615. {
  2616. constOffsets[i+1] = b.getPos();
  2617. byte tag;
  2618. b.read(tag);
  2619. switch (tag)
  2620. {
  2621. case CONSTANT_Class:
  2622. uint16_t idx;
  2623. b.read(idx);
  2624. #ifdef TRACE_CLASSFILE
  2625. DBGLOG("%u: Class %u", i+1, idx);
  2626. #endif
  2627. break;
  2628. case CONSTANT_Fieldref:
  2629. case CONSTANT_Methodref:
  2630. case CONSTANT_InterfaceMethodref:
  2631. uint16_t classIdx;
  2632. uint16_t nametypeIdx;
  2633. b.read(classIdx);
  2634. b.read(nametypeIdx);
  2635. #ifdef TRACE_CLASSFILE
  2636. DBGLOG("%u: ref(%u) class %u nametype %u", i+1, tag, classIdx, nametypeIdx);
  2637. #endif
  2638. break;
  2639. case CONSTANT_String:
  2640. #ifdef TRACE_CLASSFILE
  2641. DBGLOG("%u: Tag %u", i+1, tag);
  2642. #endif
  2643. b.skip(2);
  2644. break;
  2645. case CONSTANT_Integer:
  2646. case CONSTANT_Float:
  2647. #ifdef TRACE_CLASSFILE
  2648. DBGLOG("%u: Tag %u", i+1, tag);
  2649. #endif
  2650. b.skip(4);
  2651. break;
  2652. case CONSTANT_Long:
  2653. case CONSTANT_Double:
  2654. #ifdef TRACE_CLASSFILE
  2655. DBGLOG("%u: Tag %u", i+1, tag);
  2656. #endif
  2657. b.skip(8);
  2658. break;
  2659. case CONSTANT_NameAndType:
  2660. uint16_t nameIdx;
  2661. uint16_t descIdx;
  2662. b.read(nameIdx);
  2663. b.read(descIdx);
  2664. #ifdef TRACE_CLASSFILE
  2665. DBGLOG("%u: NameAndType(%u) name %u desc %u", i+1, tag, nameIdx, descIdx);
  2666. #endif
  2667. break;
  2668. case CONSTANT_Utf8:
  2669. // length-prefixed
  2670. uint16_t length;
  2671. b.read(length);
  2672. const byte *val;
  2673. val = b.readDirect(length);
  2674. #ifdef TRACE_CLASSFILE
  2675. DBGLOG("%u: %.*s", i+1, length, val);
  2676. #endif
  2677. break;
  2678. case CONSTANT_MethodHandle:
  2679. #ifdef TRACE_CLASSFILE
  2680. DBGLOG("%u: Tag %u", i+1, tag);
  2681. #endif
  2682. b.skip(3);
  2683. break;
  2684. case CONSTANT_MethodType:
  2685. #ifdef TRACE_CLASSFILE
  2686. DBGLOG("%u: Tag %u", i+1, tag);
  2687. #endif
  2688. b.skip(2);
  2689. break;
  2690. case CONSTANT_InvokeDynamic:
  2691. #ifdef TRACE_CLASSFILE
  2692. DBGLOG("%u: Tag %u", i+1, tag);
  2693. #endif
  2694. b.skip(4);
  2695. break;
  2696. default:
  2697. DBGLOG("Unexpected tag %u reading bytecode file", tag);
  2698. throwUnexpected();
  2699. }
  2700. }
  2701. uint16_t access_flags; b.read(access_flags);
  2702. uint16_t this_class; b.read(this_class);
  2703. uint16_t super_class; b.read(super_class);
  2704. uint16_t interfaces_count; b.read(interfaces_count);
  2705. b.skip(interfaces_count*sizeof(uint16_t));
  2706. uint16_t fields_count; b.read(fields_count);
  2707. #ifdef TRACE_CLASSFILE
  2708. DBGLOG("Access flags %x this_class=%u super_class=%u interfaces_count=%u fields_count=%u", access_flags, this_class, super_class, interfaces_count, fields_count);
  2709. #endif
  2710. for (unsigned i = 0; i < fields_count; i++)
  2711. {
  2712. b.skip(6);
  2713. uint16_t attr_count;
  2714. b.read(attr_count);
  2715. for (unsigned j = 0; j < attr_count; j++)
  2716. {
  2717. b.skip(2);
  2718. uint32_t attr_length;
  2719. b.read(attr_length);
  2720. b.skip(attr_length);
  2721. }
  2722. }
  2723. uint16_t methods_count; b.read(methods_count);
  2724. #ifdef TRACE_CLASSFILE
  2725. DBGLOG("methods_count %u", methods_count);
  2726. #endif
  2727. for (unsigned i = 0; i < methods_count; i++)
  2728. {
  2729. uint16_t flags; b.read(flags);
  2730. uint16_t name; b.read(name);
  2731. uint16_t desc; b.read(desc);
  2732. #ifdef TRACE_CLASSFILE
  2733. DBGLOG("Method %u name %u desc %u flags %x", i, name, desc, flags);
  2734. #endif
  2735. if (flags & ACC_PUBLIC)
  2736. {
  2737. StringAttr thisName;
  2738. readUtf(thisName, name);
  2739. StringAttr thisSig;
  2740. readUtf(thisSig, desc);
  2741. methodNames.append(thisName);
  2742. methodSigs.append(thisSig);
  2743. methodFlags.append(flags);
  2744. }
  2745. uint16_t attr_count;
  2746. b.read(attr_count);
  2747. for (unsigned j = 0; j < attr_count; j++)
  2748. {
  2749. b.skip(2);
  2750. uint32_t attr_length;
  2751. b.read(attr_length);
  2752. b.skip(attr_length);
  2753. }
  2754. }
  2755. /* Don't bother reading attributes as they are not really interesting to us
  2756. uint16_t attributes_count; b.read(attributes_count);
  2757. #ifdef TRACE_CLASSFILE
  2758. DBGLOG("attributes_count %u", attributes_count);
  2759. #endif
  2760. for (unsigned i = 0; i < attributes_count; i++)
  2761. {
  2762. b.skip(2);
  2763. uint32_t attr_length;
  2764. b.read(attr_length);
  2765. b.skip(attr_length);
  2766. }
  2767. #ifdef TRACE_CLASSFILE
  2768. DBGLOG("%u of %u bytes remaining", b.remaining(), b.length());
  2769. #endif
  2770. */
  2771. // Now we can find this class name
  2772. readTag(this_class, CONSTANT_Class);
  2773. readUtf(className, readIdx());
  2774. }
  2775. ~JavaClassReader()
  2776. {
  2777. delete [] constOffsets;
  2778. }
  2779. StringBuffer & getSignature(StringBuffer &ret, unsigned idx) const
  2780. {
  2781. if (!methodNames.isItem(idx))
  2782. throw makeStringException(0, "No public static method found");
  2783. ret.appendf("%s.%s:", className.get(), methodNames.item(idx));
  2784. if ((methodFlags[idx] & ACC_STATIC) == 0)
  2785. ret.append('@');
  2786. return ret.append(methodSigs.item(idx));
  2787. }
  2788. const char *queryClassName() const
  2789. {
  2790. return className.get();
  2791. }
  2792. MemoryBuffer &getEmbedData(MemoryBuffer &result, const char *funcName, bool mainClass) const
  2793. {
  2794. result.setEndian(__BIG_ENDIAN);
  2795. StringBuffer signature;
  2796. if (mainClass)
  2797. {
  2798. unsigned methodIdx = getFunctionIdx(funcName);
  2799. getSignature(signature, methodIdx);
  2800. }
  2801. else
  2802. signature.set(className);
  2803. result.append((size32_t) signature.length());
  2804. result.append(signature.length(), signature.str());
  2805. result.append((size32_t) b.length());
  2806. result.append(b);
  2807. return result;
  2808. }
  2809. enum access_flag : uint16_t
  2810. {
  2811. ACC_PUBLIC = 0x0001, // Declared public; may be accessed from outside its package.
  2812. ACC_PRIVATE = 0x0002, // Declared private; accessible only within the defining class.
  2813. ACC_PROTECTED = 0x0004, // Declared protected; may be accessed within subclasses.
  2814. ACC_STATIC = 0x0008, // Declared static.
  2815. ACC_FINAL = 0x0010, // Declared final; must not be overridden (§5.4.5).
  2816. ACC_SYNCHRONIZED = 0x0020, // Declared synchronized; invocation is wrapped by a monitor use.
  2817. ACC_BRIDGE = 0x0040, // A bridge method, generated by the compiler.
  2818. ACC_VARARGS = 0x0080, // Declared with variable number of arguments.
  2819. ACC_NATIVE = 0x0100, // Declared native; implemented in a language other than Java.
  2820. ACC_ABSTRACT = 0x0400, // Declared abstract; no implementation is provided.
  2821. ACC_STRICT = 0x0800, // Declared strictfp; floating-point mode is FP-strict.
  2822. ACC_SYNTHETIC = 0x1000, // Declared synthetic; not present in the source code.
  2823. };
  2824. unsigned getFlags(const char *funcName) const
  2825. {
  2826. unsigned idx = getFunctionIdx(funcName);
  2827. return methodFlags[idx];
  2828. }
  2829. private:
  2830. bool isConstructor(const char *name) const
  2831. {
  2832. const char *shortClass = strrchr(className, '/');
  2833. if (shortClass)
  2834. shortClass++;
  2835. else
  2836. shortClass = className;
  2837. return streq(shortClass, name);
  2838. }
  2839. unsigned getFunctionIdx(const char *funcName) const
  2840. {
  2841. if (isConstructor(funcName))
  2842. funcName = "<init>";
  2843. unsigned methodIdx = (unsigned) -1;
  2844. ForEachItemIn(idx, methodNames)
  2845. {
  2846. if (streq(funcName, methodNames[idx]))
  2847. {
  2848. if (methodIdx != (unsigned) -1)
  2849. throw makeStringExceptionV(0, "Embedded java has multiple public methods called %s", funcName);
  2850. methodIdx = idx;
  2851. }
  2852. }
  2853. if (methodIdx == (unsigned) -1)
  2854. throw makeStringExceptionV(0, "Embedded java should export a public method %s", funcName);
  2855. return methodIdx;
  2856. }
  2857. uint16_t readIdx()
  2858. {
  2859. uint16_t idx;
  2860. b.read(idx);
  2861. return idx;
  2862. }
  2863. void readTag(unsigned idx, byte expected)
  2864. {
  2865. b.reset(constOffsets[idx]);
  2866. byte tag;
  2867. b.read(tag);
  2868. assertex(tag == expected);
  2869. }
  2870. void readUtf(StringAttr &dest, unsigned idx)
  2871. {
  2872. auto savepos = b.getPos();
  2873. readTag(idx, CONSTANT_Utf8);
  2874. uint16_t length;
  2875. b.read(length);
  2876. dest.set((const char *) b.readDirect(length), length);
  2877. b.reset(savepos);
  2878. }
  2879. enum const_type
  2880. {
  2881. CONSTANT_Class = 7,
  2882. CONSTANT_Fieldref = 9,
  2883. CONSTANT_Methodref = 10,
  2884. CONSTANT_InterfaceMethodref = 11,
  2885. CONSTANT_String = 8,
  2886. CONSTANT_Integer = 3,
  2887. CONSTANT_Float = 4,
  2888. CONSTANT_Long = 5,
  2889. CONSTANT_Double = 6,
  2890. CONSTANT_NameAndType = 12,
  2891. CONSTANT_Utf8 = 1,
  2892. CONSTANT_MethodHandle = 15,
  2893. CONSTANT_MethodType = 16,
  2894. CONSTANT_InvokeDynamic = 18
  2895. };
  2896. MemoryBuffer b;
  2897. unsigned *constOffsets = nullptr;
  2898. StringAttr className;
  2899. StringArray methodNames;
  2900. StringArray methodSigs;
  2901. UnsignedArray methodFlags;
  2902. };
  2903. // Objects of class JavaEmbedImportContext are created locally for each call of a function, or thread-local to persist from one call to the next.
  2904. // Methods in here do not need to be thread-safe
  2905. class JavaEmbedImportContext : public CInterfaceOf<IEmbedFunctionContext>
  2906. {
  2907. public:
  2908. JavaEmbedImportContext(ICodeContext *codeCtx, JavaThreadContext *_sharedCtx, jobject _instance, unsigned flags, const char *options)
  2909. : sharedCtx(_sharedCtx), JNIenv(sharedCtx->JNIenv), instance(_instance)
  2910. {
  2911. if (instance)
  2912. instance = JNIenv->NewGlobalRef(instance, "instance");
  2913. argcount = 0;
  2914. argsig = NULL;
  2915. nonStatic = (instance != nullptr);
  2916. javaClass = nullptr;
  2917. StringArray opts;
  2918. opts.appendList(options, ",");
  2919. engine = codeCtx->queryEngineContext();
  2920. StringBuffer lclassPath;
  2921. if (engine)
  2922. {
  2923. const StringArray &manifestJars = engine->queryManifestFiles("jar");
  2924. ForEachItemIn(idx, manifestJars)
  2925. {
  2926. lclassPath.append(';').append(manifestJars.item(idx));
  2927. }
  2928. }
  2929. ForEachItemIn(idx, opts)
  2930. {
  2931. const char *opt = opts.item(idx);
  2932. const char *val = strchr(opt, '=');
  2933. if (val)
  2934. {
  2935. StringBuffer optName(val-opt, opt);
  2936. val++;
  2937. if (stricmp(optName, "classpath")==0)
  2938. lclassPath.append(';').append(val);
  2939. else if (strieq(optName, "persist"))
  2940. {
  2941. if (persistMode != persistNone)
  2942. throw MakeStringException(MSGAUD_user, 0, "javaembed: Persist option specified more than once");
  2943. persistMode = getPersistMode(val, globalScopeKey);
  2944. switch (persistMode)
  2945. {
  2946. case persistWorkunit:
  2947. case persistQuery:
  2948. if (!engine)
  2949. throw MakeStringException(MSGAUD_user, 0, "javaembed: Persist mode '%s' not supported here", val);
  2950. break;
  2951. }
  2952. }
  2953. else
  2954. throw MakeStringException(0, "javaembed: Unknown option %s", optName.str());
  2955. }
  2956. }
  2957. if (lclassPath.length()>1)
  2958. classpath.set(lclassPath.str()+1);
  2959. if (flags & EFthreadlocal)
  2960. sharedCtx->registerContext(this); // Do at end - otherwise an exception thrown during construction will leave this reference dangling
  2961. }
  2962. ~JavaEmbedImportContext()
  2963. {
  2964. if (javaClass)
  2965. JNIenv->DeleteGlobalRef(javaClass);
  2966. if (instance)
  2967. JNIenv->DeleteGlobalRef(instance);
  2968. if (classLoader)
  2969. JNIenv->DeleteGlobalRef(classLoader);
  2970. }
  2971. virtual bool getBooleanResult()
  2972. {
  2973. switch (*returnType)
  2974. {
  2975. case 'Z': return result.z;
  2976. case 'L':
  2977. {
  2978. // Result should be of class 'Boolean'
  2979. if (!result.l)
  2980. return false;
  2981. jmethodID getVal = JNIenv->GetMethodID(JNIenv->GetObjectClass(result.l), "booleanValue", "()Z");
  2982. if (!getVal)
  2983. throw MakeStringException(MSGAUD_user, 0, "javaembed: Type mismatch on result");
  2984. bool ret=JNIenv->CallBooleanMethod(result.l, getVal);
  2985. return ret;
  2986. }
  2987. default:
  2988. throw MakeStringException(MSGAUD_user, 0, "javaembed: Type mismatch on result");
  2989. }
  2990. }
  2991. virtual void getDataResult(size32_t &__len, void * &__result)
  2992. {
  2993. if (strcmp(returnType, "[B")!=0)
  2994. throw resultMismatchException("data");
  2995. jbyteArray array = (jbyteArray) result.l;
  2996. __len = (array != NULL ? JNIenv->GetArrayLength(array) : 0);
  2997. __result = (__len > 0 ? rtlMalloc(__len) : NULL);
  2998. if (__result)
  2999. JNIenv->GetByteArrayRegion(array, 0, __len, (jbyte *) __result);
  3000. }
  3001. virtual double getRealResult()
  3002. {
  3003. switch (*returnType)
  3004. {
  3005. case 'D': return result.d;
  3006. case 'F': return result.f;
  3007. case 'L':
  3008. {
  3009. // Result should be of class 'Number'
  3010. if (!result.l)
  3011. return 0;
  3012. jmethodID getVal = JNIenv->GetMethodID(JNIenv->GetObjectClass(result.l), "doubleValue", "()D");
  3013. if (!getVal)
  3014. throw resultMismatchException("real");
  3015. double ret = JNIenv->CallDoubleMethod(result.l, getVal);
  3016. return ret;
  3017. }
  3018. default:
  3019. throw resultMismatchException("real");
  3020. }
  3021. }
  3022. virtual __int64 getSignedResult()
  3023. {
  3024. switch (*returnType)
  3025. {
  3026. case 'B': return result.b;
  3027. case 'S': return result.s;
  3028. case 'I': return result.i;
  3029. case 'J': return result.j;
  3030. case 'L':
  3031. {
  3032. // Result should be of class 'Number'
  3033. if (!result.l)
  3034. return 0;
  3035. jmethodID getVal = JNIenv->GetMethodID(JNIenv->GetObjectClass(result.l), "longValue", "()J");
  3036. if (!getVal)
  3037. throw resultMismatchException("integer");
  3038. __int64 ret = JNIenv->CallLongMethod(result.l, getVal);
  3039. return ret;
  3040. }
  3041. default:
  3042. throw resultMismatchException("integer");
  3043. }
  3044. }
  3045. virtual unsigned __int64 getUnsignedResult()
  3046. {
  3047. if (*returnType=='L')
  3048. return (unsigned __int64) JNIenv->NewGlobalRef(result.l, "return");
  3049. else if (*returnType=='V' && strieq(methodName, "<init>"))
  3050. {
  3051. jobject thisObject = JNIenv->NewGlobalRef(result.l, "thisobject");
  3052. switch (persistMode)
  3053. {
  3054. case persistThread:
  3055. instance = thisObject; // Means we free the object automatically when this thread is done
  3056. break;
  3057. case persistWorkunit:
  3058. case persistQuery:
  3059. // Register this object to be removed automatically at end of specified scope...
  3060. assertex(engine);
  3061. VStringBuffer scopeKey("O.%p", thisObject);
  3062. PersistedObjectCriticalBlock persistBlock;
  3063. persistBlock.enter(globalState->getGlobalObject(JNIenv, scopeKey));
  3064. assertex(!persistBlock.getInstance());
  3065. engine->onTermination(JavaGlobalState::unregister, scopeKey.str(), persistMode==persistWorkunit);
  3066. persistBlock.leave(thisObject);
  3067. }
  3068. return (unsigned __int64) thisObject;
  3069. }
  3070. throw makeStringExceptionV(MSGAUD_user, 0, "javaembed: In method %s: Unsigned results not supported", queryReportName()); // Java doesn't support unsigned
  3071. }
  3072. virtual void getStringResult(size32_t &__len, char * &__result)
  3073. {
  3074. switch (*returnType)
  3075. {
  3076. case 'C': // Single char returned, prototyped as STRING or STRING1 in ECL
  3077. rtlUnicodeToStrX(__len, __result, 1, &result.c);
  3078. break;
  3079. case 'L':
  3080. {
  3081. jstring sresult = (jstring) result.l;
  3082. if (sresult)
  3083. {
  3084. size_t size = JNIenv->GetStringUTFLength(sresult); // in bytes
  3085. const char *text = JNIenv->GetStringUTFChars(sresult, NULL);
  3086. size32_t chars = rtlUtf8Length(size, text);
  3087. rtlUtf8ToStrX(__len, __result, chars, text);
  3088. JNIenv->ReleaseStringUTFChars(sresult, text);
  3089. }
  3090. else
  3091. {
  3092. __len = 0;
  3093. __result = NULL;
  3094. }
  3095. break;
  3096. }
  3097. default:
  3098. throw resultMismatchException("string");
  3099. }
  3100. }
  3101. virtual void getUTF8Result(size32_t &__chars, char * &__result)
  3102. {
  3103. switch (*returnType)
  3104. {
  3105. case 'C': // Single jchar returned, prototyped as UTF8 in ECL
  3106. rtlUnicodeToUtf8X(__chars, __result, 1, &result.c);
  3107. break;
  3108. case 'L':
  3109. {
  3110. jstring sresult = (jstring) result.l;
  3111. if (sresult)
  3112. {
  3113. size_t size = JNIenv->GetStringUTFLength(sresult); // Returns length in bytes (not chars)
  3114. const char * text = JNIenv->GetStringUTFChars(sresult, NULL);
  3115. rtlUtf8ToUtf8X(__chars, __result, rtlUtf8Length(size, text), text);
  3116. JNIenv->ReleaseStringUTFChars(sresult, text);
  3117. }
  3118. else
  3119. {
  3120. __chars = 0;
  3121. __result = NULL;
  3122. }
  3123. break;
  3124. }
  3125. default:
  3126. throw resultMismatchException("utf8");
  3127. }
  3128. }
  3129. virtual void getUnicodeResult(size32_t &__chars, UChar * &__result)
  3130. {
  3131. switch (*returnType)
  3132. {
  3133. case 'C': // Single jchar returned, prototyped as UNICODE or UNICODE1 in ECL
  3134. rtlUnicodeToUnicodeX(__chars, __result, 1, &result.c);
  3135. break;
  3136. case 'L':
  3137. {
  3138. jstring sresult = (jstring) result.l;
  3139. if (sresult)
  3140. {
  3141. size_t size = JNIenv->GetStringUTFLength(sresult); // in bytes
  3142. const char *text = JNIenv->GetStringUTFChars(sresult, NULL);
  3143. size32_t chars = rtlUtf8Length(size, text);
  3144. rtlUtf8ToUnicodeX(__chars, __result, chars, text);
  3145. JNIenv->ReleaseStringUTFChars(sresult, text);
  3146. }
  3147. else
  3148. {
  3149. __chars = 0;
  3150. __result = NULL;
  3151. }
  3152. break;
  3153. }
  3154. default:
  3155. throw resultMismatchException("unicode");
  3156. }
  3157. }
  3158. virtual void getSetResult(bool & __isAllResult, size32_t & __resultBytes, void * & __result, int _elemType, size32_t elemSize)
  3159. {
  3160. if (*returnType != '[')
  3161. throw resultMismatchException("array");
  3162. type_t elemType = (type_t) _elemType;
  3163. jarray array = (jarray) result.l;
  3164. int numResults = (array != NULL ? JNIenv->GetArrayLength(array) : 0);
  3165. rtlRowBuilder out;
  3166. byte *outData = NULL;
  3167. size32_t outBytes = 0;
  3168. if (numResults > 0)
  3169. {
  3170. if (elemSize != UNKNOWN_LENGTH)
  3171. {
  3172. out.ensureAvailable(numResults * elemSize); // MORE - check for overflow?
  3173. outData = out.getbytes();
  3174. }
  3175. switch(returnType[1])
  3176. {
  3177. case 'Z':
  3178. checkType(type_boolean, sizeof(jboolean), elemType, elemSize);
  3179. JNIenv->GetBooleanArrayRegion((jbooleanArray) array, 0, numResults, (jboolean *) outData);
  3180. break;
  3181. case 'B':
  3182. checkType(type_int, sizeof(jbyte), elemType, elemSize);
  3183. JNIenv->GetByteArrayRegion((jbyteArray) array, 0, numResults, (jbyte *) outData);
  3184. break;
  3185. case 'C':
  3186. // we COULD map to a set of string1, but is there any point?
  3187. throw MakeStringException(0, "javaembed: In method %s: Return type mismatch (char[] not supported)", queryReportName());
  3188. break;
  3189. case 'S':
  3190. checkType(type_int, sizeof(jshort), elemType, elemSize);
  3191. JNIenv->GetShortArrayRegion((jshortArray) array, 0, numResults, (jshort *) outData);
  3192. break;
  3193. case 'I':
  3194. checkType(type_int, sizeof(jint), elemType, elemSize);
  3195. JNIenv->GetIntArrayRegion((jintArray) array, 0, numResults, (jint *) outData);
  3196. break;
  3197. case 'J':
  3198. checkType(type_int, sizeof(jlong), elemType, elemSize);
  3199. JNIenv->GetLongArrayRegion((jlongArray) array, 0, numResults, (jlong *) outData);
  3200. break;
  3201. case 'F':
  3202. checkType(type_real, sizeof(jfloat), elemType, elemSize);
  3203. JNIenv->GetFloatArrayRegion((jfloatArray) array, 0, numResults, (jfloat *) outData);
  3204. break;
  3205. case 'D':
  3206. checkType(type_real, sizeof(jdouble), elemType, elemSize);
  3207. JNIenv->GetDoubleArrayRegion((jdoubleArray) array, 0, numResults, (jdouble *) outData);
  3208. break;
  3209. case 'L':
  3210. if (strcmp(returnType, "[Ljava/lang/String;") == 0)
  3211. {
  3212. for (int i = 0; i < numResults; i++)
  3213. {
  3214. jstring elem = (jstring) JNIenv->GetObjectArrayElement((jobjectArray) array, i);
  3215. size_t lenBytes = JNIenv->GetStringUTFLength(elem); // in bytes
  3216. const char *text = JNIenv->GetStringUTFChars(elem, NULL);
  3217. switch (elemType)
  3218. {
  3219. case type_string:
  3220. if (elemSize == UNKNOWN_LENGTH)
  3221. {
  3222. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  3223. outData = out.getbytes() + outBytes;
  3224. * (size32_t *) outData = lenBytes;
  3225. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  3226. outBytes += lenBytes + sizeof(size32_t);
  3227. }
  3228. else
  3229. rtlStrToStr(elemSize, outData, lenBytes, text);
  3230. break;
  3231. case type_varstring:
  3232. if (elemSize == UNKNOWN_LENGTH)
  3233. {
  3234. out.ensureAvailable(outBytes + lenBytes + 1);
  3235. outData = out.getbytes() + outBytes;
  3236. rtlStrToVStr(0, outData, lenBytes, text);
  3237. outBytes += lenBytes + 1;
  3238. }
  3239. else
  3240. rtlStrToVStr(elemSize, outData, lenBytes, text); // Fixed size null terminated strings... weird.
  3241. break;
  3242. case type_utf8:
  3243. case type_unicode:
  3244. {
  3245. size32_t numchars = rtlUtf8Length(lenBytes, text);
  3246. if (elemType == type_utf8)
  3247. {
  3248. assertex (elemSize == UNKNOWN_LENGTH);
  3249. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  3250. outData = out.getbytes() + outBytes;
  3251. * (size32_t *) outData = numchars;
  3252. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  3253. outBytes += lenBytes + sizeof(size32_t);
  3254. }
  3255. else
  3256. {
  3257. if (elemSize == UNKNOWN_LENGTH)
  3258. {
  3259. // You can't assume that number of chars in utf8 matches number in unicode16 ...
  3260. size32_t numchars16;
  3261. rtlDataAttr unicode16;
  3262. rtlUtf8ToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
  3263. out.ensureAvailable(outBytes + numchars16*sizeof(UChar) + sizeof(size32_t));
  3264. outData = out.getbytes() + outBytes;
  3265. * (size32_t *) outData = numchars16;
  3266. rtlUnicodeToUnicode(numchars16, (UChar *) (outData+sizeof(size32_t)), numchars16, unicode16.getustr());
  3267. outBytes += numchars16*sizeof(UChar) + sizeof(size32_t);
  3268. }
  3269. else
  3270. rtlUtf8ToUnicode(elemSize / sizeof(UChar), (UChar *) outData, numchars, text);
  3271. }
  3272. break;
  3273. }
  3274. default:
  3275. JNIenv->ReleaseStringUTFChars(elem, text);
  3276. throw MakeStringException(0, "javaembed: In method %s: Return type mismatch (ECL string type expected)", queryReportName());
  3277. }
  3278. JNIenv->ReleaseStringUTFChars(elem, text);
  3279. JNIenv->DeleteLocalRef(elem);
  3280. if (elemSize != UNKNOWN_LENGTH)
  3281. outData += elemSize;
  3282. }
  3283. }
  3284. else
  3285. throw MakeStringException(0, "javaembed: In method %s: Return type mismatch (%s[] not supported)", queryReportName(), returnType+2);
  3286. break;
  3287. }
  3288. }
  3289. __isAllResult = false;
  3290. __resultBytes = elemSize == UNKNOWN_LENGTH ? outBytes : elemSize * numResults;
  3291. __result = out.detachdata();
  3292. }
  3293. virtual IRowStream *getDatasetResult(IEngineRowAllocator * _resultAllocator)
  3294. {
  3295. return new JavaRowStream(result.l, _resultAllocator);
  3296. }
  3297. virtual byte * getRowResult(IEngineRowAllocator * _resultAllocator)
  3298. {
  3299. RtlDynamicRowBuilder rowBuilder(_resultAllocator);
  3300. size32_t len = getRowResult(result.l, rowBuilder);
  3301. return (byte *) rowBuilder.finalizeRowClear(len);
  3302. }
  3303. virtual size32_t getTransformResult(ARowBuilder & builder)
  3304. {
  3305. return getRowResult(result.l, builder);
  3306. }
  3307. virtual void bindBooleanParam(const char *name, bool val)
  3308. {
  3309. if (*argsig != 'Z')
  3310. typeError("BOOLEAN");
  3311. argsig++;
  3312. jvalue v;
  3313. v.z = val;
  3314. addArg(v);
  3315. }
  3316. virtual void bindDataParam(const char *name, size32_t len, const void *val)
  3317. {
  3318. if (argsig[0] != '[' || argsig[1] != 'B')
  3319. typeError("DATA");
  3320. argsig += 2;
  3321. jvalue v;
  3322. jbyteArray javaData = JNIenv->NewByteArray(len);
  3323. JNIenv->SetByteArrayRegion(javaData, 0, len, (jbyte *) val);
  3324. v.l = javaData;
  3325. addArg(v);
  3326. }
  3327. virtual void bindFloatParam(const char *name, float val)
  3328. {
  3329. // Could argue that the size should match...
  3330. jvalue v;
  3331. switch(*argsig)
  3332. {
  3333. case 'D':
  3334. v.d = val;
  3335. break;
  3336. case 'F':
  3337. v.f = val;
  3338. break;
  3339. default:
  3340. typeError("REAL");
  3341. break;
  3342. }
  3343. argsig++;
  3344. addArg(v);
  3345. }
  3346. virtual void bindRealParam(const char *name, double val)
  3347. {
  3348. jvalue v;
  3349. switch(*argsig)
  3350. {
  3351. case 'D':
  3352. v.d = val;
  3353. break;
  3354. case 'F':
  3355. v.f = val;
  3356. break;
  3357. default:
  3358. typeError("REAL");
  3359. break;
  3360. }
  3361. argsig++;
  3362. addArg(v);
  3363. }
  3364. virtual void bindSignedSizeParam(const char *name, int size, __int64 val)
  3365. {
  3366. bindSignedParam(name, val);
  3367. }
  3368. virtual void bindSignedParam(const char *name, __int64 val)
  3369. {
  3370. jvalue v;
  3371. switch(*argsig)
  3372. {
  3373. case 'I':
  3374. v.i = val;
  3375. break;
  3376. case 'J':
  3377. v.j = val;
  3378. break;
  3379. case 'S':
  3380. v.s = val;
  3381. break;
  3382. case 'B':
  3383. v.b = val;
  3384. break;
  3385. default:
  3386. typeError("INTEGER");
  3387. break;
  3388. }
  3389. argsig++;
  3390. addArg(v);
  3391. }
  3392. virtual void bindUnsignedSizeParam(const char *name, int size, unsigned __int64 val)
  3393. {
  3394. throw MakeStringException(MSGAUD_user, 0, "javaembed: In method %s: Unsigned parameters not supported", queryReportName()); // Java doesn't support unsigned
  3395. }
  3396. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  3397. {
  3398. if (!strchr(importName, '.') && argcount==0) // Could require a flag, or a special parameter name...
  3399. {
  3400. if (importName[0]=='~')
  3401. instance = (jobject) val; // Should ensure it gets released at end of function
  3402. else
  3403. instance = JNIenv->NewGlobalRef((jobject) val, "instanceParam");
  3404. if (javaClass)
  3405. {
  3406. JNIenv->DeleteGlobalRef(javaClass);
  3407. javaClass = nullptr;
  3408. }
  3409. if (classLoader)
  3410. {
  3411. JNIenv->DeleteGlobalRef(classLoader);
  3412. javaClass = nullptr;
  3413. }
  3414. loadFunction(classpath, 0, nullptr);
  3415. reinit();
  3416. }
  3417. else
  3418. {
  3419. // We could match a java class, to allow objects returned from one embed to be passed as parameters to another
  3420. throw MakeStringException(MSGAUD_user, 0, "javaembed: In method %s: Unsigned parameters not supported", queryReportName()); // Java doesn't support unsigned
  3421. }
  3422. }
  3423. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  3424. {
  3425. jvalue v;
  3426. switch(*argsig)
  3427. {
  3428. case 'C':
  3429. rtlStrToUnicode(1, &v.c, len, val);
  3430. argsig++;
  3431. break;
  3432. case 'L':
  3433. if (strncmp(argsig, "Ljava/lang/String;", 18) == 0)
  3434. {
  3435. argsig += 18;
  3436. unsigned unicodeChars;
  3437. UChar *unicode;
  3438. rtlStrToUnicodeX(unicodeChars, unicode, len, val);
  3439. v.l = JNIenv->NewString(unicode, unicodeChars);
  3440. rtlFree(unicode);
  3441. break;
  3442. }
  3443. // fall into ...
  3444. default:
  3445. typeError("STRING");
  3446. break;
  3447. }
  3448. addArg(v);
  3449. }
  3450. virtual void bindVStringParam(const char *name, const char *val)
  3451. {
  3452. bindStringParam(name, strlen(val), val);
  3453. }
  3454. virtual void bindUTF8Param(const char *name, size32_t numchars, const char *val)
  3455. {
  3456. jvalue v;
  3457. switch(*argsig)
  3458. {
  3459. case 'C':
  3460. rtlUtf8ToUnicode(1, &v.c, numchars, val);
  3461. argsig++;
  3462. break;
  3463. case 'L':
  3464. if (strncmp(argsig, "Ljava/lang/String;", 18) == 0)
  3465. {
  3466. argsig += 18;
  3467. unsigned unicodeChars;
  3468. UChar *unicode;
  3469. rtlUtf8ToUnicodeX(unicodeChars, unicode, numchars, val);
  3470. v.l = JNIenv->NewString(unicode, unicodeChars);
  3471. rtlFree(unicode);
  3472. break;
  3473. }
  3474. // fall into ...
  3475. default:
  3476. typeError("UTF8");
  3477. break;
  3478. }
  3479. addArg(v);
  3480. }
  3481. virtual void bindUnicodeParam(const char *name, size32_t numchars, const UChar *val)
  3482. {
  3483. jvalue v;
  3484. switch(*argsig)
  3485. {
  3486. case 'C':
  3487. rtlUnicodeToUnicode(1, &v.c, numchars, val);
  3488. argsig++;
  3489. break;
  3490. case 'L':
  3491. if (strncmp(argsig, "Ljava/lang/String;", 18) == 0)
  3492. {
  3493. argsig += 18;
  3494. v.l = JNIenv->NewString(val, numchars);
  3495. break;
  3496. }
  3497. // fall into ...
  3498. default:
  3499. typeError("UNICODE");
  3500. break;
  3501. }
  3502. addArg(v);
  3503. }
  3504. virtual void bindSetParam(const char *name, int _elemType, size32_t elemSize, bool isAll, size32_t totalBytes, const void *setData)
  3505. {
  3506. jvalue v;
  3507. if (*argsig != '[')
  3508. typeError("SET");
  3509. argsig++;
  3510. type_t elemType = (type_t) _elemType;
  3511. int numElems = totalBytes / elemSize;
  3512. switch(*argsig)
  3513. {
  3514. case 'Z':
  3515. checkType(type_boolean, sizeof(jboolean), elemType, elemSize);
  3516. v.l = JNIenv->NewBooleanArray(numElems);
  3517. JNIenv->SetBooleanArrayRegion((jbooleanArray) v.l, 0, numElems, (jboolean *) setData);
  3518. break;
  3519. case 'B':
  3520. checkType(type_int, sizeof(jbyte), elemType, elemSize);
  3521. v.l = JNIenv->NewByteArray(numElems);
  3522. JNIenv->SetByteArrayRegion((jbyteArray) v.l, 0, numElems, (jbyte *) setData);
  3523. break;
  3524. case 'C':
  3525. // we COULD map to a set of string1, but is there any point?
  3526. typeError("");
  3527. break;
  3528. case 'S':
  3529. checkType(type_int, sizeof(jshort), elemType, elemSize);
  3530. v.l = JNIenv->NewShortArray(numElems);
  3531. JNIenv->SetShortArrayRegion((jshortArray) v.l, 0, numElems, (jshort *) setData);
  3532. break;
  3533. case 'I':
  3534. checkType(type_int, sizeof(jint), elemType, elemSize);
  3535. v.l = JNIenv->NewIntArray(numElems);
  3536. JNIenv->SetIntArrayRegion((jintArray) v.l, 0, numElems, (jint *) setData);
  3537. break;
  3538. case 'J':
  3539. checkType(type_int, sizeof(jlong), elemType, elemSize);
  3540. v.l = JNIenv->NewLongArray(numElems);
  3541. JNIenv->SetLongArrayRegion((jlongArray) v.l, 0, numElems, (jlong *) setData);
  3542. break;
  3543. case 'F':
  3544. checkType(type_real, sizeof(jfloat), elemType, elemSize);
  3545. v.l = JNIenv->NewFloatArray(numElems);
  3546. JNIenv->SetFloatArrayRegion((jfloatArray) v.l, 0, numElems, (jfloat *) setData);
  3547. break;
  3548. case 'D':
  3549. checkType(type_real, sizeof(jdouble), elemType, elemSize);
  3550. v.l = JNIenv->NewDoubleArray(numElems);
  3551. JNIenv->SetDoubleArrayRegion((jdoubleArray) v.l, 0, numElems, (jdouble *) setData);
  3552. break;
  3553. case 'L':
  3554. if (strncmp(argsig, "Ljava/lang/String;", 18) == 0)
  3555. {
  3556. argsig += 17; // Yes, 17, because we increment again at the end of the case
  3557. const byte *inData = (const byte *) setData;
  3558. const byte *endData = inData + totalBytes;
  3559. if (elemSize == UNKNOWN_LENGTH)
  3560. {
  3561. numElems = 0;
  3562. // Will need 2 passes to work out how many elements there are in the set :(
  3563. while (inData < endData)
  3564. {
  3565. int thisSize;
  3566. switch (elemType)
  3567. {
  3568. case type_varstring:
  3569. thisSize = strlen((const char *) inData) + 1;
  3570. break;
  3571. case type_string:
  3572. thisSize = * (size32_t *) inData + sizeof(size32_t);
  3573. break;
  3574. case type_unicode:
  3575. thisSize = (* (size32_t *) inData) * sizeof(UChar) + sizeof(size32_t);
  3576. break;
  3577. case type_utf8:
  3578. thisSize = rtlUtf8Size(* (size32_t *) inData, inData + sizeof(size32_t)) + sizeof(size32_t);;
  3579. break;
  3580. default:
  3581. typeError("STRING");
  3582. }
  3583. inData += thisSize;
  3584. numElems++;
  3585. }
  3586. inData = (const byte *) setData;
  3587. }
  3588. int idx = 0;
  3589. v.l = JNIenv->NewObjectArray(numElems, langStringClass, NULL);
  3590. while (inData < endData)
  3591. {
  3592. jstring thisElem;
  3593. size32_t thisSize = elemSize;
  3594. switch (elemType)
  3595. {
  3596. case type_varstring:
  3597. {
  3598. size32_t numChars = strlen((const char *) inData);
  3599. unsigned unicodeChars;
  3600. rtlDataAttr unicode;
  3601. rtlStrToUnicodeX(unicodeChars, unicode.refustr(), numChars, (const char *) inData);
  3602. thisElem = JNIenv->NewString(unicode.getustr(), unicodeChars);
  3603. if (elemSize == UNKNOWN_LENGTH)
  3604. thisSize = numChars + 1;
  3605. break;
  3606. }
  3607. case type_string:
  3608. {
  3609. if (elemSize == UNKNOWN_LENGTH)
  3610. {
  3611. thisSize = * (size32_t *) inData;
  3612. inData += sizeof(size32_t);
  3613. }
  3614. unsigned unicodeChars;
  3615. rtlDataAttr unicode;
  3616. rtlStrToUnicodeX(unicodeChars, unicode.refustr(), thisSize, (const char *) inData);
  3617. thisElem = JNIenv->NewString(unicode.getustr(), unicodeChars);
  3618. break;
  3619. }
  3620. case type_unicode:
  3621. {
  3622. if (elemSize == UNKNOWN_LENGTH)
  3623. {
  3624. thisSize = (* (size32_t *) inData) * sizeof(UChar); // NOTE - it's in chars...
  3625. inData += sizeof(size32_t);
  3626. }
  3627. thisElem = JNIenv->NewString((const UChar *) inData, thisSize / sizeof(UChar));
  3628. break;
  3629. }
  3630. case type_utf8:
  3631. {
  3632. assertex (elemSize == UNKNOWN_LENGTH);
  3633. size32_t numChars = * (size32_t *) inData;
  3634. inData += sizeof(size32_t);
  3635. unsigned unicodeChars;
  3636. rtlDataAttr unicode;
  3637. rtlUtf8ToUnicodeX(unicodeChars, unicode.refustr(), numChars, (const char *) inData);
  3638. thisElem = JNIenv->NewString(unicode.getustr(), unicodeChars);
  3639. thisSize = rtlUtf8Size(numChars, inData);
  3640. break;
  3641. }
  3642. default:
  3643. typeError("STRING");
  3644. }
  3645. inData += thisSize;
  3646. JNIenv->SetObjectArrayElement((jobjectArray) v.l, idx, thisElem);
  3647. JNIenv->DeleteLocalRef(thisElem);
  3648. idx++;
  3649. }
  3650. }
  3651. else
  3652. typeError("");
  3653. break;
  3654. default:
  3655. throwUnexpected();
  3656. }
  3657. argsig++;
  3658. addArg(v);
  3659. }
  3660. virtual void bindRowParam(const char *name, IOutputMetaData & metaVal, const byte *val) override
  3661. {
  3662. if (*argsig != 'L') // should tell us the type of the object we need to create to pass in
  3663. typeError("RECORD");
  3664. // Class name is from the char after the L up to the first ;
  3665. const char *tail = strchr(argsig, ';');
  3666. if (!tail)
  3667. typeError("RECORD");
  3668. StringAttr className(argsig+1, tail - (argsig+1));
  3669. argsig = tail+1;
  3670. const RtlTypeInfo *typeInfo = metaVal.queryTypeInfo();
  3671. assertex(typeInfo);
  3672. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  3673. JavaObjectBuilder javaBuilder((CheckedJNIEnv *)JNIenv, &dummyField, loadClass(className));
  3674. typeInfo->process(val, val, &dummyField, javaBuilder); // Creates a java object from the incoming ECL row
  3675. jvalue v;
  3676. v.l = javaBuilder.getObject();
  3677. addArg(v);
  3678. }
  3679. virtual IInterface *bindParamWriter(IInterface *esdl, const char *esdlservice, const char *esdltype, const char *name)
  3680. {
  3681. if (*argsig != 'L') // should tell us the type of the object we need to create to pass in
  3682. typeError("OBJECT");
  3683. // Class name is from the char after the L up to the first ;
  3684. const char *tail = strchr(argsig, ';');
  3685. if (!tail)
  3686. typeError("OBJECT");
  3687. StringAttr className(argsig+1, tail - (argsig+1));
  3688. argsig = tail+1;
  3689. Owned<JavaXmlBuilder> writer = new JavaXmlBuilder(JNIenv, dynamic_cast<IEsdlDefinition*>(esdl), esdlservice, esdltype);
  3690. writer->initWriter();
  3691. return (IXmlWriter*)writer.getClear();
  3692. }
  3693. virtual void paramWriterCommit(IInterface *writer)
  3694. {
  3695. JavaXmlBuilder *javaWriter = dynamic_cast<JavaXmlBuilder*>(writer);
  3696. if (!javaWriter)
  3697. throw MakeStringException(0, "javaembed: Invalid object writer for %s", signature.get());
  3698. jvalue v;
  3699. v.l = javaWriter->getObject();
  3700. addArg(v);
  3701. }
  3702. virtual void bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val)
  3703. {
  3704. jvalue v;
  3705. char argsigStart = *argsig;
  3706. switch (argsigStart)
  3707. {
  3708. case '[':
  3709. case '<':
  3710. ++argsig;
  3711. break;
  3712. case 'L':
  3713. if (strncmp(argsig, "Ljava/util/Iterator<", 20) == 0)
  3714. {
  3715. argsig += 20;
  3716. break;
  3717. }
  3718. /* no break */
  3719. default:
  3720. typeError("DATASET");
  3721. }
  3722. if (*argsig != 'L') // should tell us the type of the object we need to create to pass in
  3723. typeError("DATASET");
  3724. // Class name is from the char after the L up to the first ;
  3725. const char *tail = strchr(argsig, ';');
  3726. if (!tail)
  3727. typeError("RECORD");
  3728. StringAttr className(argsig+1, tail - (argsig+1));
  3729. argsig = tail+1;
  3730. if (argsigStart=='L')
  3731. {
  3732. if (argsig[0] != '>' || argsig[1] != ';')
  3733. typeError("DATASET");
  3734. argsig += 2;
  3735. }
  3736. if (argsigStart=='[')
  3737. {
  3738. // Pass in an array of objects
  3739. PointerArrayOf<_jobject> allRows;
  3740. const RtlTypeInfo *typeInfo = metaVal.queryTypeInfo();
  3741. assertex(typeInfo);
  3742. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  3743. jclass Class = loadClass(className);
  3744. JavaObjectBuilder javaBuilder((CheckedJNIEnv *) JNIenv, &dummyField, Class);
  3745. for (;;)
  3746. {
  3747. roxiemem::OwnedConstRoxieRow thisRow = val->ungroupedNextRow();
  3748. if (!thisRow)
  3749. break;
  3750. const byte *brow = (const byte *) thisRow.get();
  3751. typeInfo->process(brow, brow, &dummyField, javaBuilder); // Creates a java object from the incoming ECL row
  3752. allRows.append(javaBuilder.getObject());
  3753. }
  3754. jobjectArray array = JNIenv->NewObjectArray(allRows.length(), Class, NULL);
  3755. ForEachItemIn(idx, allRows)
  3756. {
  3757. JNIenv->SetObjectArrayElement(array, idx, allRows.item(idx));
  3758. }
  3759. v.l = array;
  3760. }
  3761. else
  3762. {
  3763. // Pass in an iterator
  3764. // Create a java object of type com.HPCCSystems.HpccUtils - this acts as a proxy for the iterator
  3765. JNIenv->ExceptionClear();
  3766. jvalue param;
  3767. const RtlTypeInfo *typeInfo = metaVal.queryTypeInfo();
  3768. ECLDatasetIterator *iterator = new ECLDatasetIterator((CheckedJNIEnv *) JNIenv, typeInfo, loadClass(className), val);
  3769. param.j = (jlong) iterator;
  3770. iterators.append(*iterator);
  3771. jobject proxy = JNIenv->NewObject(hpccIteratorClass, hi_constructor, param, JNIenv->NewStringUTF(helperLibraryName));
  3772. v.l = proxy;
  3773. }
  3774. addArg(v);
  3775. }
  3776. virtual void writeResult(IInterface *esdl, const char *esdlservice, const char *esdltype, IInterface *writer)
  3777. {
  3778. return sharedCtx->writeObjectResult(result.l, dynamic_cast<IEsdlDefinition*>(esdl), esdlservice, esdltype, dynamic_cast<IXmlWriter*>(writer));
  3779. }
  3780. virtual void importFunction(size32_t lenChars, const char *utf) override
  3781. {
  3782. if (!javaClass)
  3783. {
  3784. size32_t bytes = rtlUtf8Size(lenChars, utf);
  3785. importName.set(utf, bytes);
  3786. if (strchr(importName, '.'))
  3787. loadFunction(classpath, 0, nullptr);
  3788. }
  3789. if (javaClass)
  3790. reinit();
  3791. }
  3792. IException *translateException(IException *E)
  3793. {
  3794. StringBuffer msg;
  3795. E->errorMessage(msg);
  3796. const char *text = msg;
  3797. if (strncmp(text, "javaembed: ", 11)==0)
  3798. text += 11;
  3799. auto code = E->errorCode();
  3800. auto aud = E->errorAudience();
  3801. E->Release();
  3802. return makeStringExceptionV(aud, code, "javaembed: In method %s: %s", queryReportName(), text);
  3803. }
  3804. IException *resultMismatchException(const char *expected)
  3805. {
  3806. return makeStringExceptionV(0, "javaembed: In method %s: Type mismatch on result (%s expected)", queryReportName(), expected);
  3807. }
  3808. virtual void callFunction()
  3809. {
  3810. try
  3811. {
  3812. if (*argsig != ')')
  3813. throw MakeStringException(0, "Too few ECL parameters passed for Java signature %s", signature.get());
  3814. JNIenv->ExceptionClear();
  3815. if (nonStatic)
  3816. {
  3817. if (!instance)
  3818. {
  3819. if (streq(methodName, "<init>"))
  3820. {
  3821. result.l = JNIenv->NewObjectA(javaClass, javaMethodID, args);
  3822. return;
  3823. }
  3824. assertex(persistMode == persistNone);
  3825. instance = createInstance();
  3826. }
  3827. if (javaMethodID)
  3828. {
  3829. switch (*returnType)
  3830. {
  3831. case 'C': result.c = JNIenv->CallCharMethodA(instance, javaMethodID, args); break;
  3832. case 'Z': result.z = JNIenv->CallBooleanMethodA(instance, javaMethodID, args); break;
  3833. case 'J': result.j = JNIenv->CallLongMethodA(instance, javaMethodID, args); break;
  3834. case 'F': result.f = JNIenv->CallFloatMethodA(instance, javaMethodID, args); break;
  3835. case 'D': result.d = JNIenv->CallDoubleMethodA(instance, javaMethodID, args); break;
  3836. case 'I': result.i = JNIenv->CallIntMethodA(instance, javaMethodID, args); break;
  3837. case 'S': result.s = JNIenv->CallShortMethodA(instance, javaMethodID, args); break;
  3838. case 'B': result.s = JNIenv->CallByteMethodA(instance, javaMethodID, args); break;
  3839. case '[':
  3840. case 'L': result.l = JNIenv->CallObjectMethodA(instance, javaMethodID, args); break;
  3841. case 'V': JNIenv->CallVoidMethodA(instance, javaMethodID, args); result.l = nullptr; break;
  3842. default: throwUnexpected();
  3843. }
  3844. }
  3845. else
  3846. {
  3847. assertex(methodName[0]=='~');
  3848. result.l = 0;
  3849. }
  3850. }
  3851. else
  3852. {
  3853. switch (*returnType)
  3854. {
  3855. case 'C': result.c = JNIenv->CallStaticCharMethodA(javaClass, javaMethodID, args); break;
  3856. case 'Z': result.z = JNIenv->CallStaticBooleanMethodA(javaClass, javaMethodID, args); break;
  3857. case 'J': result.j = JNIenv->CallStaticLongMethodA(javaClass, javaMethodID, args); break;
  3858. case 'F': result.f = JNIenv->CallStaticFloatMethodA(javaClass, javaMethodID, args); break;
  3859. case 'D': result.d = JNIenv->CallStaticDoubleMethodA(javaClass, javaMethodID, args); break;
  3860. case 'I': result.i = JNIenv->CallStaticIntMethodA(javaClass, javaMethodID, args); break;
  3861. case 'S': result.s = JNIenv->CallStaticShortMethodA(javaClass, javaMethodID, args); break;
  3862. case 'B': result.s = JNIenv->CallStaticByteMethodA(javaClass, javaMethodID, args); break;
  3863. case '[':
  3864. case 'L': result.l = JNIenv->CallStaticObjectMethodA(javaClass, javaMethodID, args); break;
  3865. case 'V': JNIenv->CallStaticVoidMethodA(javaClass, javaMethodID, args); result.l = nullptr; break;
  3866. default: throwUnexpected();
  3867. }
  3868. }
  3869. }
  3870. catch (IException *E)
  3871. {
  3872. throw translateException(E);
  3873. }
  3874. }
  3875. virtual void compileEmbeddedScript(size32_t lenChars, const char *_script)
  3876. {
  3877. throwUnexpected();
  3878. }
  3879. virtual void loadCompiledScript(size32_t bytecodeLen, const void *bytecode) override
  3880. {
  3881. if (!javaClass)
  3882. {
  3883. MemoryBuffer b;
  3884. b.setBuffer(bytecodeLen, (void *) bytecode, false);
  3885. b.setEndian(__BIG_ENDIAN);
  3886. uint32_t siglen; b.read(siglen);
  3887. const char *sig = (const char *) b.readDirect(siglen);
  3888. size32_t bytes = rtlUtf8Size(siglen, sig); // MORE - check that this size is serialized in chars not bytes!
  3889. importName.set(sig, bytes);
  3890. loadFunction(classpath, bytecodeLen, (const byte *) bytecode);
  3891. }
  3892. reinit();
  3893. }
  3894. virtual void enter() override
  3895. {
  3896. // If we rejig codegen to only call loadCompiledScript etc at construction time, then this will need to do the reinit()
  3897. // until we do, it's too early
  3898. // Create a new frame for local references and increase the capacity
  3899. // of those references to 64 (default is 16)
  3900. JNIenv->PushLocalFrame(64);
  3901. }
  3902. virtual void exit() override
  3903. {
  3904. if (persistMode == persistNone && instance != nullptr)
  3905. {
  3906. JNIenv->DeleteGlobalRef(instance);
  3907. instance = nullptr;
  3908. }
  3909. JNIenv->PopLocalFrame(nullptr);
  3910. #ifdef CHECK_JNI
  3911. forceGC(JNIenv);
  3912. #endif
  3913. }
  3914. protected:
  3915. __declspec(noreturn) void typeError(const char *ECLtype) __attribute__((noreturn))
  3916. {
  3917. const char *javaType;
  3918. int javaLen = 0;
  3919. switch (*argsig)
  3920. {
  3921. case 'Z': javaType = "boolean"; break;
  3922. case 'B': javaType = "byte"; break;
  3923. case 'C': javaType = "char"; break;
  3924. case 'S': javaType = "short"; break;
  3925. case 'I': javaType = "int"; break;
  3926. case 'J': javaType = "long"; break;
  3927. case 'F': javaType = "float"; break;
  3928. case 'D': javaType = "double"; break;
  3929. case '[': javaType = "array"; break;
  3930. case 'L':
  3931. {
  3932. javaType = argsig+1;
  3933. const char *semi = strchr(argsig, ';');
  3934. if (semi)
  3935. javaLen = semi - javaType;
  3936. break;
  3937. }
  3938. case ')':
  3939. throw MakeStringException(0, "javaembed: In method %s: Too many ECL parameters passed for Java signature", queryReportName());
  3940. default:
  3941. throw MakeStringException(0, "javaembed: In method %s: Unrecognized character %c in Java signature", queryReportName(), *argsig);
  3942. }
  3943. if (!javaLen)
  3944. javaLen = strlen(javaType);
  3945. throw MakeStringException(0, "javaembed: In Method %s: ECL type %s cannot be passed to Java type %.*s", queryReportName(), ECLtype, javaLen, javaType);
  3946. }
  3947. void addArg(jvalue &arg)
  3948. {
  3949. assertex(argcount < MAX_JNI_ARGS);
  3950. args[argcount] = arg;
  3951. argcount++;
  3952. }
  3953. size32_t getRowResult(jobject result, ARowBuilder &builder)
  3954. {
  3955. const RtlTypeInfo *typeInfo = builder.queryAllocator()->queryOutputMeta()->queryTypeInfo();
  3956. assertex(typeInfo);
  3957. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  3958. JavaRowBuilder javaRowBuilder((CheckedJNIEnv *) JNIenv, &dummyField, result);
  3959. return typeInfo->build(builder, 0, &dummyField, javaRowBuilder);
  3960. }
  3961. jclass loadClass(const char *className)
  3962. {
  3963. JNIenv->ExceptionClear();
  3964. jmethodID loadClassMethod = JNIenv->GetMethodID(JNIenv->GetObjectClass(classLoader), "loadClass","(Ljava/lang/String;)Ljava/lang/Class;");
  3965. jstring classNameString = JNIenv->NewStringUTF(className);
  3966. jclass Class = (jclass) JNIenv->CallObjectMethod(classLoader, loadClassMethod, classNameString);
  3967. return Class;
  3968. }
  3969. const char *queryReportName()
  3970. {
  3971. if (!importName.length())
  3972. return "";
  3973. const char *report = strrchr(importName.get(), '/');
  3974. if (report)
  3975. report++;
  3976. else
  3977. report = importName.get();
  3978. return report;
  3979. }
  3980. jobject createThreadClassLoader(const char *classPath, size32_t bytecodeLen, const byte *bytecode)
  3981. {
  3982. if (bytecodeLen || (classPath && *classPath))
  3983. {
  3984. jstring jClassPath = (classPath && *classPath) ? JNIenv->NewStringUTF(classPath) : nullptr;
  3985. jobject helperName = JNIenv->NewStringUTF(helperLibraryName);
  3986. jobject contextClassLoaderObj = JNIenv->CallStaticObjectMethod(customLoaderClass, clc_newInstance, jClassPath, sharedCtx->getSystemClassLoader(), bytecodeLen, (uint64_t) bytecode, helperName);
  3987. assertex(contextClassLoaderObj);
  3988. return contextClassLoaderObj;
  3989. }
  3990. else
  3991. {
  3992. return sharedCtx->getSystemClassLoader();
  3993. }
  3994. }
  3995. jobject createInstance()
  3996. {
  3997. jmethodID constructor;
  3998. try
  3999. {
  4000. constructor = JNIenv->GetMethodID(javaClass, "<init>", "()V");
  4001. }
  4002. catch (IException *E)
  4003. {
  4004. Owned<IException> e = E;
  4005. throw MakeStringException(0, "parameterless constructor required");
  4006. }
  4007. return JNIenv->NewGlobalRef(JNIenv->NewObject(javaClass, constructor), "createInstance");
  4008. }
  4009. void loadFunction(const char *classpath, size32_t bytecodeLen, const byte *bytecode)
  4010. {
  4011. try
  4012. {
  4013. StringBuffer classname;
  4014. // Name should be in the form class.method:signature
  4015. const char *funcname = strrchr(importName, '.');
  4016. if (funcname)
  4017. {
  4018. classname.append(funcname-importName, importName);
  4019. classname.replace('/', '.');
  4020. funcname++; // skip the '.'
  4021. }
  4022. else
  4023. {
  4024. nonStatic = true; // we assume we are going to call a method of a cached object - and we will get the class from that
  4025. funcname = importName;
  4026. }
  4027. const char *sig = strchr(funcname, ':');
  4028. if (sig)
  4029. {
  4030. methodName.set(funcname, sig-funcname);
  4031. sig++; // skip the ':'
  4032. if (*sig == '@') // indicates a non-static method
  4033. {
  4034. nonStatic = true;
  4035. sig++;
  4036. }
  4037. signature.set(sig);
  4038. }
  4039. else
  4040. methodName.set(funcname);
  4041. bool isConstructor = streq(methodName, "<init>");
  4042. {
  4043. PersistedObjectCriticalBlock persistBlock;
  4044. StringBuffer scopeKey;
  4045. if (nonStatic && !instance && persistMode > persistThread && !isConstructor) // MORE - there may be a persist mode between Thread and Wuid, meaning shared between multiple on this thread
  4046. {
  4047. // If the persist scope is global, query, or workunit, we may want to use a pre-existing object. If we do we share its classloader, class, etc.
  4048. getScopeKey(scopeKey);
  4049. persistBlock.enter(globalState->getGlobalObject(JNIenv, scopeKey));
  4050. instance = persistBlock.getInstance();
  4051. if (instance)
  4052. persistBlock.leave();
  4053. }
  4054. if (instance)
  4055. {
  4056. javaClass = (jclass) JNIenv->NewGlobalRef(JNIenv->GetObjectClass(instance), "javaClass");
  4057. classLoader = JNIenv->NewGlobalRef(getClassLoader(JNIenv, javaClass), "classLoader");
  4058. sharedCtx->setThreadClassLoader(classLoader);
  4059. }
  4060. if (!javaClass)
  4061. {
  4062. if (!classname)
  4063. throw MakeStringException(MSGAUD_user, 0, "Invalid import name - Expected classname.methodname:signature");
  4064. classLoader = JNIenv->NewGlobalRef(createThreadClassLoader(classpath, bytecodeLen, bytecode), "classLoader");
  4065. sharedCtx->setThreadClassLoader(classLoader);
  4066. jmethodID loadClassMethod = JNIenv->GetMethodID(JNIenv->GetObjectClass(classLoader), "loadClass","(Ljava/lang/String;)Ljava/lang/Class;");
  4067. try
  4068. {
  4069. javaClass = (jclass) JNIenv->CallObjectMethod(classLoader, loadClassMethod, JNIenv->NewStringUTF(classname));
  4070. }
  4071. catch (IException *E)
  4072. {
  4073. Owned<IException> e = E;
  4074. throw makeWrappedExceptionV(E, E->errorCode(), "Failed to resolve class name %s", classname.str());
  4075. }
  4076. javaClass = (jclass) JNIenv->NewGlobalRef(javaClass, "javaClass");
  4077. }
  4078. if (nonStatic && !instance && !isConstructor && persistMode != persistNone)
  4079. {
  4080. instance = createInstance();
  4081. if (persistBlock.locked())
  4082. {
  4083. if (persistMode==persistQuery || persistMode==persistWorkunit)
  4084. {
  4085. assertex(engine);
  4086. engine->onTermination(JavaGlobalState::unregister, scopeKey.str(), persistMode==persistWorkunit);
  4087. }
  4088. persistBlock.leave(JNIenv->NewGlobalRef(instance, "persistBlockLeave"));
  4089. }
  4090. }
  4091. }
  4092. if (methodName[0]=='~')
  4093. {
  4094. if (!instance)
  4095. throw MakeStringException(0, "~ invalid without instance");
  4096. StringBuffer myClassName;
  4097. getClassNameForObject(JNIenv, myClassName, instance);
  4098. const char *shortClassName = strrchr(myClassName, '.');
  4099. if (shortClassName)
  4100. shortClassName++;
  4101. else
  4102. shortClassName = myClassName;
  4103. if (!streq(methodName+1, shortClassName))
  4104. throw MakeStringException(0, "class name %s does not match", shortClassName);
  4105. signature.set("()L"); // We return 0
  4106. }
  4107. else
  4108. {
  4109. if (!signature)
  4110. getSignature(signature, JNIenv, javaClass, funcname);
  4111. StringBuffer javaSignature;
  4112. patchSignature(javaSignature, signature);
  4113. if (nonStatic)
  4114. javaMethodID = JNIenv->GetMethodID(javaClass, methodName, javaSignature);
  4115. else
  4116. javaMethodID = JNIenv->GetStaticMethodID(javaClass, methodName, javaSignature);
  4117. }
  4118. returnType = strrchr(signature, ')');
  4119. assertex(returnType); // Otherwise how did Java accept it??
  4120. returnType++;
  4121. }
  4122. catch(IException *E)
  4123. {
  4124. throw translateException(E);
  4125. }
  4126. }
  4127. static StringBuffer &patchSignature(StringBuffer &ret, const char *signature)
  4128. {
  4129. // We need to patch up the provided signature - any instances of <classname; need to be replaced by Ljava.utils.iterator
  4130. const char *finger = signature;
  4131. while (finger && *finger)
  4132. {
  4133. if (*finger == '<')
  4134. {
  4135. // If there is a corresponding >, assume it's the 'extended' form and just strip out the bit from < to >
  4136. const char *close = strchr(finger, '>');
  4137. if (close)
  4138. finger = close;
  4139. else
  4140. {
  4141. ret.append("Ljava/util/Iterator;");
  4142. finger = strchr(finger, ';');
  4143. if (!finger)
  4144. throw MakeStringException(MSGAUD_user, 0, "javaembed: Invalid java function signature %s", signature);
  4145. }
  4146. }
  4147. else
  4148. ret.append(*finger);
  4149. finger++;
  4150. }
  4151. return ret;
  4152. }
  4153. StringBuffer &getScopeKey(StringBuffer &ret)
  4154. {
  4155. if (globalScopeKey)
  4156. ret.append(globalScopeKey);
  4157. else
  4158. {
  4159. // MORE - we could key off the class name, but we don't always supply that.
  4160. // Plus it's mangled as often as not
  4161. const char *dotpos = strrchr(importName, '.');
  4162. if (dotpos)
  4163. ret.append(dotpos-importName+1, importName);
  4164. else
  4165. throw MakeStringException(0, "javaembed: cannot determine key for persist in function %s", importName.get());
  4166. }
  4167. ret.append('.');
  4168. switch (persistMode)
  4169. {
  4170. case persistGlobal:
  4171. ret.append("global");
  4172. break;
  4173. case persistWorkunit:
  4174. engine->getQueryId(ret, true);
  4175. break;
  4176. case persistQuery:
  4177. engine->getQueryId(ret, false);
  4178. break;
  4179. }
  4180. return ret;
  4181. }
  4182. JavaThreadContext *sharedCtx = nullptr;
  4183. CheckedJNIEnv *JNIenv = nullptr;
  4184. jvalue result = {0};
  4185. StringAttr classpath;
  4186. IArrayOf<ECLDatasetIterator> iterators; // to make sure they get freed
  4187. bool nonStatic = false;
  4188. jobject instance = nullptr; // class instance of object to call methods on
  4189. StringAttr globalScopeKey;
  4190. PersistMode persistMode = persistNone; // Defines the lifetime of the java object for which this is called.
  4191. // The following members are set up the first time a method is called only
  4192. IEngineContext *engine = nullptr;
  4193. jclass javaClass = nullptr;
  4194. jobject classLoader = nullptr;
  4195. jmethodID javaMethodID = nullptr;
  4196. StringAttr methodName;
  4197. StringAttr importName;
  4198. StringAttr signature;
  4199. const char *returnType = nullptr; // A pointer within signature
  4200. // These point to the current arg/signature byte as we are binding
  4201. int argcount = 0;
  4202. jvalue args[MAX_JNI_ARGS];
  4203. const char *argsig = nullptr; // A pointer within signature
  4204. void reinit()
  4205. {
  4206. argcount = 0;
  4207. argsig = signature;
  4208. assertex(*argsig == '(');
  4209. argsig++;
  4210. }
  4211. };
  4212. static __thread JavaThreadContext* threadContext; // We reuse per thread, for speed
  4213. static __thread ThreadTermFunc threadHookChain;
  4214. static void releaseContext()
  4215. {
  4216. if (threadContext)
  4217. {
  4218. delete threadContext;
  4219. threadContext = NULL;
  4220. }
  4221. if (threadHookChain)
  4222. {
  4223. (*threadHookChain)();
  4224. threadHookChain = NULL;
  4225. }
  4226. }
  4227. static JavaThreadContext *queryContext()
  4228. {
  4229. if (!threadContext)
  4230. {
  4231. threadContext = new JavaThreadContext;
  4232. threadHookChain = addThreadTermFunc(releaseContext);
  4233. }
  4234. return threadContext;
  4235. }
  4236. static CheckedJNIEnv *queryJNIEnv()
  4237. {
  4238. return queryContext()->JNIenv;
  4239. }
  4240. class JavaEmbedServiceContext : public CInterfaceOf<IEmbedServiceContext>
  4241. {
  4242. public:
  4243. JavaEmbedServiceContext(JavaThreadContext *_sharedCtx, const char *service, const char *_options)
  4244. : sharedCtx(_sharedCtx), Class(0), options(_options), className(service), object(0)
  4245. {
  4246. StringArray opts;
  4247. opts.appendList(options, ",");
  4248. ForEachItemIn(idx, opts)
  4249. {
  4250. const char *opt = opts.item(idx);
  4251. const char *val = strchr(opt, '=');
  4252. if (val)
  4253. {
  4254. StringBuffer optName(val-opt, opt);
  4255. val++;
  4256. if (strieq(optName, "classpath"))
  4257. classpath.set(val);
  4258. else
  4259. throw MakeStringException(0, "javaembed: Unknown option %s", optName.str());
  4260. }
  4261. }
  4262. }
  4263. ~JavaEmbedServiceContext()
  4264. {
  4265. if (object)
  4266. sharedCtx->JNIenv->DeleteGlobalRef(object);
  4267. if (Class)
  4268. sharedCtx->JNIenv->DeleteGlobalRef(Class);
  4269. }
  4270. void init()
  4271. {
  4272. jobject classLoader = sharedCtx->getThreadClassLoader();
  4273. jmethodID loadClassMethod = sharedCtx->JNIenv->GetMethodID(sharedCtx->JNIenv->GetObjectClass(classLoader), "loadClass","(Ljava/lang/String;)Ljava/lang/Class;");
  4274. jstring methodString = sharedCtx->JNIenv->NewStringUTF(className);
  4275. Class = (jclass) sharedCtx->JNIenv->NewGlobalRef(sharedCtx->JNIenv->CallObjectMethod(classLoader, loadClassMethod, methodString), "Class");
  4276. jmethodID constructor = sharedCtx->JNIenv->GetMethodID(Class, "<init>", "()V");
  4277. object = sharedCtx->JNIenv->NewGlobalRef(sharedCtx->JNIenv->NewObject(Class, constructor), "constructed");
  4278. }
  4279. virtual IEmbedFunctionContext *createFunctionContext(const char *function)
  4280. {
  4281. if (!object)
  4282. return NULL;
  4283. Owned<JavaEmbedImportContext> fctx = new JavaEmbedImportContext(nullptr, queryContext(), object, 0, options);
  4284. fctx->importFunction(rtlUtf8Length(strlen(function), function), function);
  4285. return fctx.getClear();
  4286. }
  4287. protected:
  4288. JavaThreadContext *sharedCtx;
  4289. StringBuffer className;
  4290. jclass Class;
  4291. jobject object;
  4292. StringAttr classpath;
  4293. StringAttr options;
  4294. };
  4295. class JavaEmbedContext : public CInterfaceOf<IEmbedContext>
  4296. {
  4297. public:
  4298. virtual IEmbedFunctionContext *createFunctionContext(unsigned flags, const char *options) override
  4299. {
  4300. return createFunctionContextEx(nullptr, nullptr, flags, options);
  4301. }
  4302. virtual IEmbedFunctionContext *createFunctionContextEx(ICodeContext * ctx, const IThorActivityContext *activityCtx, unsigned flags, const char *options) override
  4303. {
  4304. return new JavaEmbedImportContext(ctx, queryContext(), nullptr, flags, options);
  4305. }
  4306. virtual IEmbedServiceContext *createServiceContext(const char *service, unsigned flags, const char *options) override
  4307. {
  4308. Owned<JavaEmbedServiceContext> serviceContext = new JavaEmbedServiceContext(queryContext(), service, options);
  4309. serviceContext->init();
  4310. return serviceContext.getClear();
  4311. }
  4312. };
  4313. static JavaEmbedContext embedContext;
  4314. extern DECL_EXPORT IEmbedContext* queryEmbedContext()
  4315. {
  4316. return &embedContext;
  4317. }
  4318. extern DECL_EXPORT IEmbedContext* getEmbedContext()
  4319. {
  4320. return new JavaEmbedContext;
  4321. }
  4322. static bool isValidIdentifier(const char *source)
  4323. {
  4324. return isalnum(*source) || *source=='_' || *source=='$' || ::readUtf8Size(source)>1; // This is not strictly accurate but probably good enough
  4325. }
  4326. static bool isFullClassFile(StringBuffer &className, bool &seenPublic, size32_t len, const char *source)
  4327. {
  4328. // A heuristic to determine whether the supplied embedded source is a full class file or just a single method
  4329. // Basically, if we see keyword "class" before we see { then we assume it's a full file
  4330. // Also track whether the public keyword has been supplied
  4331. bool inLineComment = false;
  4332. bool inBlockComment = false;
  4333. seenPublic = false;
  4334. while (len)
  4335. {
  4336. if (inLineComment)
  4337. {
  4338. if (*source=='\n')
  4339. inLineComment = false;
  4340. }
  4341. else if (inBlockComment)
  4342. {
  4343. if (*source=='*' && len > 1 && source[1]=='/')
  4344. {
  4345. inBlockComment = false;
  4346. len--;
  4347. source++;
  4348. }
  4349. }
  4350. else switch(*source)
  4351. {
  4352. case '/':
  4353. if (len > 1)
  4354. {
  4355. if (source[1]=='*')
  4356. {
  4357. inBlockComment = true;
  4358. len--;
  4359. source++;
  4360. }
  4361. else if (source[1]=='/')
  4362. inLineComment = true;
  4363. }
  4364. break;
  4365. case '{':
  4366. return false;
  4367. default:
  4368. if (isValidIdentifier(source))
  4369. {
  4370. const char *start = source;
  4371. while (len && isValidIdentifier(source))
  4372. {
  4373. source+=::readUtf8Size(source);
  4374. len--;
  4375. }
  4376. if (source-start == 5 && memcmp(start, "class", source-start)==0)
  4377. {
  4378. while (len && isspace(*source)) // MORE - a comment between the keyword and the classname will fail - tough.
  4379. {
  4380. source += ::readUtf8Size(source);
  4381. len--;
  4382. }
  4383. start = source;
  4384. while (len && isValidIdentifier(source))
  4385. {
  4386. source += ::readUtf8Size(source);
  4387. len--;
  4388. }
  4389. className.append(source-start, start);
  4390. return true;
  4391. }
  4392. else if (source-start == 6 && memcmp(start, "public", source-start)==0)
  4393. seenPublic = true;
  4394. }
  4395. if (!len)
  4396. return false;
  4397. break;
  4398. }
  4399. source += ::readUtf8Size(source);
  4400. len--;
  4401. }
  4402. // If we get here then it doesn't have a { at all - we COULD say it needs the prototype too but for now, who knows...
  4403. return false;
  4404. }
  4405. static bool suppressJavaError(const char *err)
  4406. {
  4407. if (!err || !*err)
  4408. return true;
  4409. if (streq(err, "1 error"))
  4410. return true;
  4411. char *rest;
  4412. if (strtoul(err, &rest, 10) && streq(rest, " errors"))
  4413. return true;
  4414. return false;
  4415. }
  4416. static StringBuffer & cleanupJavaError(StringBuffer &ret, StringBuffer &prefix, const char *err, unsigned lineNumberOffset)
  4417. {
  4418. // Remove filename (as it's generated) and fix up line number. Errors that do not have line number use previous error's line number.
  4419. const char *colon = strchr(err, ':');
  4420. // Java errors are a bit of a pain - if you suppress the ones without line numbers you get too little information, if you don't you get too much
  4421. if (colon && isdigit(colon[1]))
  4422. {
  4423. char *end;
  4424. unsigned lineno = strtoul(colon+1, &end, 10) - lineNumberOffset;
  4425. prefix.clear().appendf("(%u,1)", lineno);
  4426. ret.append(prefix).append(end);
  4427. }
  4428. else if (!suppressJavaError(err))
  4429. ret.append(prefix).appendf(": error: %s", err);
  4430. return ret;
  4431. }
  4432. static void cleanupJavaErrors(StringBuffer &ret, const char *errors, unsigned lineNumberOffset)
  4433. {
  4434. StringArray errlines;
  4435. errlines.appendList(errors, "\n", false);
  4436. StringBuffer prefix;
  4437. ForEachItemIn(idx, errlines)
  4438. {
  4439. StringBuffer cleaned;
  4440. cleanupJavaError(cleaned, prefix, errlines.item(idx), lineNumberOffset);
  4441. if (cleaned.length())
  4442. ret.append(cleaned).append('\n');
  4443. }
  4444. }
  4445. static thread_local unsigned prevHash = 0;
  4446. static thread_local MemoryBuffer prevCompile;
  4447. void doPrecompile(size32_t & __lenResult, void * & __result, const char *funcName, size32_t charsBody, const char * body, const char *argNames, const char *compilerOptions, const char *persistOptions, StringBuffer &errors, bool checking)
  4448. {
  4449. unsigned sizeBody = rtlUtf8Size(charsBody, body); // size in bytes
  4450. unsigned hash = rtlHash32Data(sizeBody,body,0xcafebabe);
  4451. if (hash==prevHash) // Reusing result from the syntax check that normally immediately precedes a precompile
  4452. {
  4453. __lenResult = prevCompile.length();
  4454. __result = prevCompile.detachOwn();
  4455. prevHash = 0;
  4456. return;
  4457. }
  4458. StringAttr globalScope;
  4459. PersistMode persistMode = getPersistMode(persistOptions, globalScope);
  4460. StringBuffer tmpDirName;
  4461. getTempFilePath(tmpDirName, "javaembed", nullptr);
  4462. tmpDirName.append(PATHSEPCHAR).append("tmp.XXXXXX");
  4463. if (!mkdtemp((char *) tmpDirName.str()))
  4464. throw makeStringExceptionV(0, "Failed to create temporary directory %s (error %d)", tmpDirName.str(), errno);
  4465. Owned<IFile> tempDir = createIFile(tmpDirName);
  4466. StringBuffer classname;
  4467. bool seenPublic = false;
  4468. bool isFullClass = isFullClassFile(classname, seenPublic, charsBody, body); // note - we pass in length in characters, not bytes
  4469. if (!isFullClass)
  4470. classname.set("embed");
  4471. VStringBuffer javafile("%s" PATHSEPSTR "%s.java", tmpDirName.str(), classname.str());
  4472. FILE *source = fopen(javafile.str(), "wt");
  4473. fprintf(source, "package com.HPCCSystems.embed.x%x;\n", hash);
  4474. unsigned lineNumberOffset = 1; // for the /n above
  4475. if (isFullClass)
  4476. fprintf(source, "%.*s", sizeBody, body);
  4477. else
  4478. {
  4479. if (seenPublic)
  4480. fprintf(source, "public class embed\n{\n %.*s\n}", sizeBody, body);
  4481. else
  4482. fprintf(source, "public class embed\n{\n public static %.*s\n}", sizeBody, body);
  4483. lineNumberOffset += 2; // for the /n's above
  4484. }
  4485. fclose(source);
  4486. MemoryBuffer result;
  4487. Owned<IPipeProcess> pipe = createPipeProcess();
  4488. VStringBuffer javac("javac %s %s", isEmptyString(compilerOptions) ? "-g:none" : compilerOptions, javafile.str());
  4489. if (!pipe->run("javac", javac, tmpDirName, false, false, true, 0, false))
  4490. {
  4491. throw makeStringException(0, "Failed to run javac");
  4492. }
  4493. else
  4494. {
  4495. StringBuffer javaErrors;
  4496. Owned<ISimpleReadStream> pipeReader = pipe->getErrorStream();
  4497. readSimpleStream(javaErrors, *pipeReader);
  4498. pipe->closeError();
  4499. unsigned retcode = pipe->wait();
  4500. cleanupJavaErrors(errors, javaErrors, lineNumberOffset);
  4501. if (retcode)
  4502. throw makeStringException(0, "Failed to precompile java code");
  4503. VStringBuffer mainfile("%s" PATHSEPSTR "%s.class", tmpDirName.str(), classname.str());
  4504. JavaClassReader reader(mainfile);
  4505. DBGLOG("Analysing generated class %s", reader.queryClassName());
  4506. // Not sure how useful this warning is.
  4507. //if (persistMode > persistThread && (reader.getFlags(funcName) & JavaClassReader::ACC_SYNCHRONIZED)==0)
  4508. // errors.appendf("Warning: persist mode set but function is not synchronized\n");
  4509. reader.getEmbedData(result, funcName, true);
  4510. removeFileTraceIfFail(mainfile);
  4511. // Now read nested classes
  4512. Owned<IDirectoryIterator> classFiles = tempDir->directoryFiles("*$*.class",false,false);
  4513. ForEach(*classFiles)
  4514. {
  4515. const char *thisFile = classFiles->query().queryFilename();
  4516. JavaClassReader reader(thisFile);
  4517. reader.getEmbedData(result, nullptr, false);
  4518. removeFileTraceIfFail(thisFile);
  4519. }
  4520. // We could give a warning if persist is set to anything over "thread" and the function we are calling is not synchronized.
  4521. }
  4522. removeFileTraceIfFail(javafile);
  4523. tempDir->remove();
  4524. __lenResult = result.length();
  4525. __result = result.detachOwn();
  4526. }
  4527. extern DECL_EXPORT void precompile(size32_t & __lenResult, void * & __result, const char *funcName, size32_t charsBody, const char * body, const char *argNames, const char *compilerOptions, const char *persistOptions)
  4528. {
  4529. StringBuffer errors;
  4530. doPrecompile(__lenResult, __result, funcName, charsBody, body, argNames, compilerOptions, persistOptions, errors, false);
  4531. }
  4532. extern DECL_EXPORT void syntaxCheck(size32_t & __lenResult, char * & __result, const char *funcname, size32_t charsBody, const char * body, const char *argNames, const char *compilerOptions, const char *persistOptions)
  4533. {
  4534. StringBuffer result;
  4535. try
  4536. {
  4537. size32_t ds;
  4538. rtlDataAttr d;
  4539. StringBuffer errors;
  4540. doPrecompile(ds, d.refdata(), funcname, charsBody, body, argNames, compilerOptions, persistOptions, result, true);
  4541. // Reuse result in the precompile that normally immediately follows
  4542. unsigned sizeBody = rtlUtf8Size(charsBody, body); // size in bytes
  4543. prevHash = rtlHash32Data(sizeBody,body,0xcafebabe);
  4544. prevCompile.setBuffer(ds, d.detachdata(), true);
  4545. }
  4546. catch (IException *E)
  4547. {
  4548. StringBuffer msg;
  4549. result.append(E->errorMessage(msg));
  4550. E->Release();
  4551. }
  4552. __lenResult = result.length();
  4553. __result = result.detach();
  4554. }
  4555. extern DECL_EXPORT void checkImport(size32_t & __lenResult, char * & __result, const char *funcname, size32_t charsImport, const char * import, const char *argNames, const char *compilerOptions, const char *persistOptions)
  4556. {
  4557. StringBuffer result;
  4558. try
  4559. {
  4560. StringAttr globalScope;
  4561. PersistMode persistMode = getPersistMode(persistOptions, globalScope);
  4562. if (persistMode > persistThread && !globalScope)
  4563. {
  4564. StringBuffer b(rtlUtf8Size(charsImport, import), import);
  4565. const char *dotpos = strrchr(b, '.');
  4566. if (!dotpos)
  4567. throw MakeStringException(0, "javaembed: cannot determine key for persist in function %s", b.str());
  4568. }
  4569. }
  4570. catch (IException *E)
  4571. {
  4572. StringBuffer msg;
  4573. result.appendf("%s\n", E->errorMessage(msg).str());
  4574. E->Release();
  4575. }
  4576. __lenResult = result.length();
  4577. __result = result.detach();
  4578. }
  4579. } // namespace
  4580. // Callbacks from java
  4581. extern "C" {
  4582. JNIEXPORT jboolean JNICALL Java_com_HPCCSystems_HpccUtils__1hasNext (JNIEnv *, jclass, jlong);
  4583. JNIEXPORT jobject JNICALL Java_com_HPCCSystems_HpccUtils__1next (JNIEnv *, jclass, jlong);
  4584. JNIEXPORT jclass JNICALL Java_com_HPCCSystems_HpccClassLoader_defineClassForEmbed(JNIEnv *env, jobject loader, jint bytecodeLen, jlong bytecode, jstring name);
  4585. }
  4586. JNIEXPORT jboolean JNICALL Java_com_HPCCSystems_HpccUtils__1hasNext (JNIEnv *JNIenv, jclass, jlong proxy)
  4587. {
  4588. try
  4589. {
  4590. javaembed::ECLDatasetIterator *e = (javaembed::ECLDatasetIterator *) proxy;
  4591. return e->hasNext();
  4592. }
  4593. catch (IException *E)
  4594. {
  4595. StringBuffer msg;
  4596. E->errorMessage(msg);
  4597. E->Release();
  4598. JNIenv->ThrowNew(javaembed::langIllegalArgumentExceptionClass, msg.str());
  4599. return false;
  4600. }
  4601. }
  4602. JNIEXPORT jobject JNICALL Java_com_HPCCSystems_HpccUtils__1next (JNIEnv *JNIenv, jclass, jlong proxy)
  4603. {
  4604. try
  4605. {
  4606. javaembed::ECLDatasetIterator *e = (javaembed::ECLDatasetIterator *) proxy;
  4607. return e->next();
  4608. }
  4609. catch (IException *E)
  4610. {
  4611. StringBuffer msg;
  4612. E->errorMessage(msg);
  4613. E->Release();
  4614. JNIenv->ThrowNew(javaembed::langIllegalArgumentExceptionClass, msg.str());
  4615. return NULL;
  4616. }
  4617. }
  4618. JNIEXPORT jclass JNICALL Java_com_HPCCSystems_HpccClassLoader_defineClassForEmbed(JNIEnv *env, jobject loader, jint datalen, jlong data, jstring name)
  4619. {
  4620. const char *nameChars = env->GetStringUTFChars(name, nullptr);
  4621. size32_t namelen = strlen(nameChars);
  4622. MemoryBuffer b;
  4623. b.setBuffer(datalen, (void *) data, false);
  4624. b.setEndian(__BIG_ENDIAN);
  4625. jclass ret = nullptr;
  4626. while (b.remaining())
  4627. {
  4628. uint32_t siglen; b.read(siglen);
  4629. const char *sig = (const char *) b.readDirect(siglen);
  4630. uint32_t bytecodeLen; b.read(bytecodeLen);
  4631. const jbyte * bytecode = (const jbyte *) b.readDirect(bytecodeLen);
  4632. if (siglen >= namelen && memcmp(sig, nameChars, namelen)==0 && (namelen == siglen || sig[namelen] == '.'))
  4633. {
  4634. #ifdef TRACE_CLASSFILE
  4635. DBGLOG("javaembed: loading class %s (%.*s)", nameChars, siglen, sig);
  4636. #endif
  4637. ret = env->DefineClass(nameChars, loader, bytecode, bytecodeLen);
  4638. // NOTE - if there is an exception it will get thrown next time we get into java code
  4639. break;
  4640. }
  4641. }
  4642. if (!ret)
  4643. DBGLOG("javaembed: Failed to load class %s", nameChars);
  4644. env->ReleaseStringUTFChars(name, nameChars);
  4645. return ret;
  4646. }
  4647. // Used for dynamically loading in ESDL
  4648. extern "C" DECL_EXPORT IEmbedContext *getEmbedContextDynamic()
  4649. {
  4650. return javaembed::getEmbedContext();
  4651. }