forked from hpcc-systems/HPCC-Platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavaembed.cpp
More file actions
3309 lines (3193 loc) · 121 KB
/
javaembed.cpp
File metadata and controls
3309 lines (3193 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#include "platform.h"
#include <jni.h>
#include "jexcept.hpp"
#include "jthread.hpp"
#include "hqlplugins.hpp"
#include "deftype.hpp"
#include "eclhelper.hpp"
#include "eclrtl.hpp"
#include "eclrtl_imp.hpp"
#include "rtlfield.hpp"
#include "rtlds_imp.hpp"
#include "jprop.hpp"
#include "build-config.h"
#include "roxiemem.hpp"
#include "nbcd.hpp"
#include "rtlformat.hpp"
#include "esdl_def.hpp"
#ifndef _WIN32
#include <sys/resource.h>
#endif
static const char * compatibleVersions[] = {
"Java Embed Helper 1.0.0",
NULL };
static const char *version = "Java Embed Helper 1.0.0";
extern "C" DECL_EXPORT bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
{
if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
{
ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
pbx->compatibleVersions = compatibleVersions;
}
else if (pb->size != sizeof(ECLPluginDefinitionBlock))
return false;
pb->magicVersion = PLUGIN_VERSION;
pb->version = version;
pb->moduleName = "java";
pb->ECL = NULL;
pb->flags = PLUGIN_MULTIPLE_VERSIONS;
pb->description = "Java Embed Helper";
return true;
}
__declspec(noreturn) static void UNSUPPORTED(const char *feature) __attribute__((noreturn));
static void UNSUPPORTED(const char *feature)
{
throw MakeStringException(-1, "UNSUPPORTED feature: %s not supported in java plugin", feature);
}
namespace javaembed {
// Use a global object to ensure that the Java VM is initialized once only.
// We would like to create it lazily for two reasons:
// 1. So that we only get a JVM if we need one (even if we have loaded the plugin)
// 2. It's important for the JVM to be initialized AFTER we have set up signal handlers, as it
// likes to set its own (in particular, it seems to intercept and ignore some SIGSEGV during the
// garbage collection).
// Unfortunately, it seems that the design of the JNI interface is such that JNI_CreateJavaVM has to be called on the 'main thread'.
// 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
// any engines that call InitModuleObjects() or load plugins dynamically do so AFTER setting any signal handlers or calling
// EnableSEHtoExceptionMapping
//
static class JavaGlobalState
{
public:
JavaGlobalState()
{
JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
StringArray optionStrings;
const char* origPath = getenv("CLASSPATH");
StringBuffer newPath;
newPath.append("-Djava.class.path=");
if (origPath && *origPath)
{
newPath.append(origPath).append(ENVSEPCHAR);
}
const IProperties &conf = queryEnvironmentConf();
if (conf.hasProp("classpath"))
{
conf.getProp("classpath", newPath);
newPath.append(ENVSEPCHAR);
}
else
{
newPath.append(INSTALL_DIR).append(PATHSEPCHAR).append("classes").append(ENVSEPCHAR);
}
newPath.append(".");
optionStrings.append(newPath);
if (conf.hasProp("jvmlibpath"))
{
StringBuffer libPath;
libPath.append("-Djava.library.path=");
conf.getProp("jvmlibpath", libPath);
optionStrings.append(libPath);
}
// Options we should set (but allow for override with jvmoptions below)
optionStrings.append("-XX:-UseLargePages");
if (conf.hasProp("jvmoptions"))
{
// Use space as field sep as ':' and ';' are valid
optionStrings.appendList(conf.queryProp("jvmoptions"), " ");
}
// Options we know we always want set
optionStrings.append("-Xrs");
#ifdef RLIMIT_STACK
// JVM has a habit of reducing the stack limit on main thread to 1M - probably dates back to when it was actually an increase...
StringBuffer stackOption("-Xss");
struct rlimit limit;
rlim_t slim = 0;
if (getrlimit (RLIMIT_STACK, &limit)==0)
slim = limit.rlim_cur;
if (!slim)
slim = 8*1024*1024;
if (slim >= 1*1024*1024)
{
stackOption.append((__uint64) slim);
optionStrings.append(stackOption);
}
#endif
// These may be useful for debugging
#ifdef _DEBUG
// optionStrings.append("-Xcheck:jni");
// optionStrings.append("-verbose:jni");
#endif
JavaVMOption* options = new JavaVMOption[optionStrings.length()];
ForEachItemIn(idx, optionStrings)
{
// DBGLOG("javaembed: Setting JVM option: %s",(char *)optionStrings.item(idx));
options[idx].optionString = (char *) optionStrings.item(idx);
options[idx].extraInfo = NULL;
}
vm_args.nOptions = optionStrings.length();
vm_args.options = options;
vm_args.ignoreUnrecognized = true;
vm_args.version = JNI_VERSION_1_6;
/* load and initialize a Java VM, return a JNI interface pointer in env */
JNIEnv *env; /* receives pointer to native method interface */
int createResult = JNI_CreateJavaVM(&javaVM, (void**)&env, &vm_args);
delete [] options;
if (createResult != 0)
throw MakeStringException(0, "javaembed: Unable to initialize JVM (%d)",createResult);
}
~JavaGlobalState()
{
// We don't attempt to destroy the Java VM, as it's buggy...
}
JavaVM *javaVM; /* denotes a Java VM */
} *globalState;
static StringBuffer helperLibraryName;
#ifdef _WIN32
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#endif
MODULE_INIT(INIT_PRIORITY_STANDARD)
{
globalState = new JavaGlobalState;
// Make sure we are never unloaded (as JVM does not support it)
// we do this by doing a dynamic load of the javaembed library
#ifdef _WIN32
char ln[_MAX_PATH];
::GetModuleFileName((HINSTANCE)&__ImageBase, ln, _MAX_PATH);
if (strstr(path, "javaembed"))
{
HINSTANCE h = LoadSharedObject(ln, false, false);
helperLibraryName.set(ln);
DBGLOG("LoadSharedObject returned %p", h);
}
#else
if (findLoadedModule(helperLibraryName, "javaembed"))
{
HINSTANCE h = LoadSharedObject(helperLibraryName, false, false);
// Deliberately leak this handle
}
#endif
return true;
}
MODULE_EXIT()
{
// We don't attempt to destroy the Java VM, as it's buggy...
// delete globalState;
// globalState = NULL;
}
static void checkType(type_t javatype, size32_t javasize, type_t ecltype, size32_t eclsize)
{
if (javatype != ecltype || javasize != eclsize)
throw MakeStringException(0, "javaembed: Type mismatch"); // MORE - could provide some details!
}
static void checkException(JNIEnv *JNIenv, bool fail=true)
{
if (JNIenv->ExceptionCheck())
{
jthrowable exception = JNIenv->ExceptionOccurred();
JNIenv->ExceptionClear();
jclass throwableClass = JNIenv->FindClass("java/lang/Throwable");
jmethodID throwableToString = JNIenv->GetMethodID(throwableClass, "toString", "()Ljava/lang/String;");
jstring cause = (jstring) JNIenv->CallObjectMethod(exception, throwableToString);
const char *text = JNIenv->GetStringUTFChars(cause, 0);
VStringBuffer message("javaembed: %s", text);
JNIenv->ReleaseStringUTFChars(cause, text);
if (fail)
rtlFail(0, message);
throw MakeStringExceptionDirect(0, message);
}
}
//-------------------------------------------
// A JavaObject accessor has common functionality shared by both the builders below (Java-> ECL and ECL->Java)
class JavaObjectAccessor : public CInterface
{
protected:
JavaObjectAccessor(JNIEnv *_JNIenv, const RtlFieldInfo *_outerRow, jobject _row)
: JNIenv(_JNIenv), row(_row), outerRow(_outerRow), idx(0), limit(0), inSet(false), inDataSet(false)
{
Class = (jclass) JNIenv->NewGlobalRef(JNIenv->GetObjectClass(row));
}
JavaObjectAccessor(JNIEnv *_JNIenv, const RtlFieldInfo *_outerRow)
: JNIenv(_JNIenv), outerRow(_outerRow), idx(0), limit(0), inSet(false), inDataSet(false)
{
row = NULL;
Class = NULL;
}
~JavaObjectAccessor()
{
// Unwind anything left on the stack (in case we had exceptions), to make sure the Class we release is the global one
if (stack.length())
Class = (jclass) stack.item(0);
if (Class)
JNIenv->DeleteGlobalRef(Class);
}
void push()
{
stack.append(Class);
stack.append(row);
}
void pop()
{
row = (jobject) stack.popGet();
Class = (jclass) stack.popGet();
}
jfieldID getFieldId(const RtlFieldInfo * field, const char *sig, const char *expected)
{
// MORE - if we are going to stream a dataset we really should be caching these somehow
JNIenv->ExceptionClear();
jfieldID fieldId = 0;
if (sig)
{
if (inSet)
{
VStringBuffer arraySig("[%s", sig);
fieldId = JNIenv->GetFieldID(Class, field->name, arraySig.str());
}
else
fieldId = JNIenv->GetFieldID(Class, field->name, sig);
}
else
{
// Do it the hard way via reflection API
// Equivalent java:
// Field field = object.getClass().getDeclaredField(fieldName);
jclass classClass =JNIenv->GetObjectClass(Class);
checkException();
jmethodID getDeclaredField = JNIenv->GetMethodID(classClass, "getDeclaredField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;" );
checkException();
jstring fieldName = JNIenv->NewStringUTF(field->name);
checkException();
jobject reflectedField = JNIenv->CallObjectMethod(Class, getDeclaredField, fieldName);
checkException();
fieldId = JNIenv->FromReflectedField(reflectedField);
}
if (!fieldId && expected)
throw MakeStringException(0, "javaembed: Unable to retrieve field %s of type %s", field->name, expected);
if (expected)
checkException();
else
JNIenv->ExceptionClear();
return fieldId;
}
void checkException()
{
javaembed::checkException(JNIenv);
}
JNIEnv *JNIenv;
jobject row;
const RtlFieldInfo *outerRow;
jclass Class;
ConstPointerArray stack;
unsigned idx;
UnsignedArray idxStack;
unsigned limit;
bool inSet;
bool inDataSet;
};
// A JavaRowBuilder object is used to construct an ECL row from a Java object
class JavaRowBuilder : public JavaObjectAccessor, implements IFieldSource
{
public:
IMPLEMENT_IINTERFACE;
JavaRowBuilder(JNIEnv *_JNIenv, const RtlFieldInfo *_outerRow, jobject _row)
: JavaObjectAccessor(_JNIenv, _outerRow, _row)
{
}
virtual bool getBooleanResult(const RtlFieldInfo *field)
{
jboolean b;
if (inSet)
{
JNIenv->GetBooleanArrayRegion((jbooleanArray) row, idx, 1, &b);
}
else
{
jfieldID fieldId = getFieldId(field, "Z", "boolean");
b = JNIenv->GetBooleanField(row, fieldId);
}
checkException();
return b;
}
virtual void getDataResult(const RtlFieldInfo *field, size32_t &__len, void * &__result)
{
jbyteArray array;
if (inSet)
{
array = (jbyteArray) JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
}
else
{
jfieldID fieldId = getFieldId(field, "[B", "DATA");
array = (jbyteArray) JNIenv->GetObjectField(row, fieldId);
}
checkException();
__len = (array != NULL ? JNIenv->GetArrayLength(array) : 0);
__result = (__len > 0 ? rtlMalloc(__len) : NULL);
if (__result)
JNIenv->GetByteArrayRegion(array, 0, __len, (jbyte *) __result);
checkException();
}
virtual double getRealResult(const RtlFieldInfo *field)
{
double d;
if (inSet)
{
float f;
switch (field->size(NULL, NULL))
{
case 4:
JNIenv->GetFloatArrayRegion((jfloatArray) row, idx, 1, &f);
d = f;
break;
case 8:
JNIenv->GetDoubleArrayRegion((jdoubleArray) row, idx, 1, &d);
break;
default:
throwUnexpected();
}
}
else
{
jfieldID fieldId;
switch (field->size(NULL, NULL))
{
case 4:
fieldId = getFieldId(field, "F", "float");
d = JNIenv->GetFloatField(row, fieldId);
break;
case 8:
fieldId = getFieldId(field, "D", "double");
d = JNIenv->GetDoubleField(row, fieldId);
break;
default:
throwUnexpected();
}
}
checkException();
return d;
}
virtual __int64 getSignedResult(const RtlFieldInfo *field)
{
__int64 ret;
if (inSet)
{
jbyte b;
jshort s;
jint i;
jlong l;
switch (field->size(NULL, NULL))
{
case 1:
JNIenv->GetByteArrayRegion((jbyteArray) row, idx, 1, &b);
ret = b;
break;
case 2:
JNIenv->GetShortArrayRegion((jshortArray) row, idx, 1, &s);
ret = s;
break;
case 4:
JNIenv->GetIntArrayRegion((jintArray) row, idx, 1, &i);
ret = i;
break;
case 8:
JNIenv->GetLongArrayRegion((jlongArray) row, idx, 1, &l);
ret = l;
break;
default:
UNSUPPORTED("non-standard integer sizes");
}
}
else
{
jfieldID fieldId;
switch (field->size(NULL, NULL))
{
case 1:
fieldId = getFieldId(field, "B", "byte");
ret = JNIenv->GetByteField(row, fieldId);
break;
case 2:
fieldId = getFieldId(field, "S", "short");
ret = JNIenv->GetShortField(row, fieldId);
break;
case 4:
fieldId = getFieldId(field, "I", "int");
ret = JNIenv->GetIntField(row, fieldId);
break;
case 8:
fieldId = getFieldId(field, "J", "long");
ret = JNIenv->GetLongField(row, fieldId);
break;
default:
UNSUPPORTED("non-standard integer sizes");
}
}
checkException();
return ret;
}
virtual unsigned __int64 getUnsignedResult(const RtlFieldInfo *field)
{
UNSUPPORTED("unsigned fields"); // No unsigned types in Java
}
virtual void getStringResult(const RtlFieldInfo *field, size32_t &__len, char * &__result)
{
jstring result;
if (inSet)
{
// MORE - set of string1 mapping to Java array of char ? Not sure it's worth it.
result = (jstring) JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
}
else
{
if (field->isFixedSize() && field->size(NULL, NULL)==1)
{
// See if there's a char field
jfieldID charFieldId = getFieldId(field, "C", NULL);
if (charFieldId)
{
jchar resultChar = JNIenv->GetCharField(row, charFieldId);
rtlUnicodeToStrX(__len, __result, 1, &resultChar);
return;
}
}
jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
result = (jstring) JNIenv->GetObjectField(row, fieldId);
}
if (!result)
{
__len = 0;
__result = NULL;
return;
}
size_t size = JNIenv->GetStringUTFLength(result); // in bytes
const char *text = JNIenv->GetStringUTFChars(result, NULL);
size32_t chars = rtlUtf8Length(size, text);
rtlUtf8ToStrX(__len, __result, chars, text);
JNIenv->ReleaseStringUTFChars(result, text);
JNIenv->DeleteLocalRef(result);
}
virtual void getUTF8Result(const RtlFieldInfo *field, size32_t &__len, char * &__result)
{
jstring result;
if (inSet)
{
// MORE - set of string1 mapping to Java array of char ? Not sure it's worth it.
result = (jstring) JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
}
else
{
if (field->isFixedSize() && field->size(NULL, NULL)==1)
{
// See if there's a char field
jfieldID charFieldId = getFieldId(field, "C", NULL);
if (charFieldId)
{
jchar resultChar = JNIenv->GetCharField(row, charFieldId);
rtlUnicodeToUtf8X(__len, __result, 1, &resultChar);
return;
}
}
jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
result = (jstring) JNIenv->GetObjectField(row, fieldId);
}
if (!result)
{
__len = 0;
__result = NULL;
return;
}
size_t size = JNIenv->GetStringUTFLength(result); // in bytes
const char *text = JNIenv->GetStringUTFChars(result, NULL);
size32_t chars = rtlUtf8Length(size, text);
rtlUtf8ToUtf8X(__len, __result, chars, text);
JNIenv->ReleaseStringUTFChars(result, text);
JNIenv->DeleteLocalRef(result);
}
virtual void getUnicodeResult(const RtlFieldInfo *field, size32_t &__len, UChar * &__result)
{
jstring result;
if (inSet)
{
// MORE - set of string1 mapping to Java array of char ? Not sure it's worth it.
result = (jstring) JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
}
else
{
if (field->isFixedSize() && field->size(NULL, NULL)==1)
{
// See if there's a char field
jfieldID charFieldId = getFieldId(field, "C", NULL);
if (charFieldId)
{
jchar resultChar = JNIenv->GetCharField(row, charFieldId);
rtlUnicodeToUnicodeX(__len, __result, 1, &resultChar);
return;
}
}
jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
result = (jstring) JNIenv->GetObjectField(row, fieldId);
}
if (!result)
{
__len = 0;
__result = NULL;
return;
}
size_t size = JNIenv->GetStringUTFLength(result); // in bytes
const char *text = JNIenv->GetStringUTFChars(result, NULL);
size32_t chars = rtlUtf8Length(size, text);
rtlUtf8ToUnicodeX(__len, __result, chars, text);
JNIenv->ReleaseStringUTFChars(result, text);
JNIenv->DeleteLocalRef(result);
}
virtual void getDecimalResult(const RtlFieldInfo *field, Decimal &value)
{
double ret = getRealResult(field);
value.setReal(ret);
}
virtual void processBeginSet(const RtlFieldInfo * field, bool &isAll)
{
isAll = false; // No concept of an 'all' set in Java
push();
jfieldID fieldId = getFieldId(field, NULL, "object"); // We assume it will be an array, but not sure of what...
row = JNIenv->GetObjectField(row, fieldId);
inSet = true;
idx = -1; // First call to next() increments it to 0
limit = row != NULL ? JNIenv->GetArrayLength((jarray) row) : 0;
checkException();
}
virtual bool processNextSet(const RtlFieldInfo * field)
{
assertex(inSet);
idx++;
return idx < limit;
}
virtual void processBeginDataset(const RtlFieldInfo * field)
{
push();
jfieldID fieldId = getFieldId(field, NULL, "object"); // We assume it will be an array, but not sure of what...
row = JNIenv->GetObjectField(row, fieldId);
inDataSet = true;
idx = -1; // First call to next() increments it to 0
limit = row != NULL ? JNIenv->GetArrayLength((jarray) row) : 0;
checkException();
}
virtual void processBeginRow(const RtlFieldInfo * field)
{
if (field != outerRow)
{
push();
if (inDataSet)
{
row = JNIenv->GetObjectArrayElement((jobjectArray) row, idx);
}
else
{
jfieldID fieldId = getFieldId(field, NULL, "object");
row = JNIenv->GetObjectField(row, fieldId);
}
if (!row)
rtlFail(0, "javaembed: child dataset object should not be NULL");
Class = JNIenv->GetObjectClass(row);
}
}
virtual bool processNextRow(const RtlFieldInfo * field)
{
assertex(inDataSet);
idx++;
return idx < limit;
}
virtual void processEndSet(const RtlFieldInfo * field)
{
inSet = false;
JNIenv->DeleteLocalRef(row);
pop();
}
virtual void processEndDataset(const RtlFieldInfo * field)
{
inDataSet = false;
JNIenv->DeleteLocalRef(row);
pop();
}
virtual void processEndRow(const RtlFieldInfo * field)
{
if (field != outerRow)
{
JNIenv->DeleteLocalRef(row);
JNIenv->DeleteLocalRef(Class);
pop();
}
}
};
//-------------------------------------------
// A JavaObjectBuilder object is used to construct a Java object from an ECL row
class JavaObjectBuilder : public JavaObjectAccessor, implements IFieldProcessor
{
public:
IMPLEMENT_IINTERFACE;
JavaObjectBuilder(JNIEnv *_JNIenv, const RtlFieldInfo *_outerRow, const char *className)
: JavaObjectAccessor(_JNIenv, _outerRow)
{
JNIenv->ExceptionClear();
Class = (jclass) JNIenv->NewGlobalRef(JNIenv->FindClass(className)); // MORE - should use the custom classloader, once that fix is merged
checkException();
setConstructor();
}
virtual void processString(unsigned numchars, const char *text, const RtlFieldInfo * field)
{
if (field->isFixedSize() && field->size(NULL, NULL)==1 && !inSet) // SET OF STRING1 is not mapped to array of char...
{
// See if there's a char field
jfieldID charFieldId = getFieldId(field, "C", NULL);
if (charFieldId)
{
assertex(numchars==1);
jchar c;
rtlStrToUnicode(1, &c, 1, text);
JNIenv->SetCharField(row, charFieldId, c);
checkException();
return;
}
}
jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
size32_t numchars16;
rtlDataAttr unicode16;
rtlStrToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
jstring value = JNIenv->NewString(unicode16.getustr(), numchars16);
checkException();
if (inSet)
JNIenv->SetObjectArrayElement((jobjectArray) row, idx, value);
else
JNIenv->SetObjectField(row, fieldId, value);
JNIenv->DeleteLocalRef(value);
checkException();
}
virtual void processBool(bool value, const RtlFieldInfo * field)
{
jfieldID fieldId = getFieldId(field, "Z", "boolean");
JNIenv->SetBooleanField(row, fieldId, value);
checkException();
}
virtual void processData(unsigned len, const void *value, const RtlFieldInfo * field)
{
jfieldID fieldId = getFieldId(field, "[B", "data");
jbyteArray javaData = JNIenv->NewByteArray(len);
JNIenv->SetByteArrayRegion(javaData, 0, len, (jbyte *) value);
checkException();
if (inSet)
JNIenv->SetObjectArrayElement((jobjectArray) row, idx, javaData);
else
JNIenv->SetObjectField(row, fieldId, javaData);
checkException();
}
virtual void processInt(__int64 value, const RtlFieldInfo * field)
{
jfieldID fieldId;
switch (field->size(NULL, NULL))
{
case 1:
fieldId = getFieldId(field, "B", "byte");
JNIenv->SetByteField(row, fieldId, value);
break;
case 2:
fieldId = getFieldId(field, "S", "short");
JNIenv->SetShortField(row, fieldId, value);
break;
case 4:
fieldId = getFieldId(field, "I", "int");
JNIenv->SetIntField(row, fieldId, value);
break;
case 8:
fieldId = getFieldId(field, "J", "long");
JNIenv->SetLongField(row, fieldId, value);
break;
default:
UNSUPPORTED("non-standard integer sizes");
break;
}
checkException();
}
virtual void processUInt(unsigned __int64 value, const RtlFieldInfo * field)
{
UNSUPPORTED("unsigned fields"); // No unsigned types in Java
}
virtual void processReal(double value, const RtlFieldInfo * field)
{
jfieldID fieldId;
switch (field->size(NULL, NULL))
{
case 4:
fieldId = getFieldId(field, "F", "float");
JNIenv->SetFloatField(row, fieldId, (float) value);
break;
case 8:
fieldId = getFieldId(field, "D", "double");
JNIenv->SetDoubleField(row, fieldId, value);
break;
default:
throwUnexpected();
}
checkException();
}
virtual void processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
{
// we could map to doubles, but probably better to let the ECL programmer do that themselves
UNSUPPORTED("DECIMAL fields");
}
virtual void processUDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
{
UNSUPPORTED("UDECIMAL fields");
}
virtual void processUnicode(unsigned numchars, const UChar *text, const RtlFieldInfo * field)
{
jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
jstring value = JNIenv->NewString(text, numchars);
checkException();
if (inSet)
JNIenv->SetObjectArrayElement((jobjectArray) row, idx, value);
else
JNIenv->SetObjectField(row, fieldId, value);
JNIenv->DeleteLocalRef(value);
checkException();
}
virtual void processQString(unsigned len, const char *value, const RtlFieldInfo * field)
{
size32_t charCount;
rtlDataAttr text;
rtlQStrToStrX(charCount, text.refstr(), len, value);
processString(charCount, text.getstr(), field);
}
virtual void processUtf8(unsigned numchars, const char *text, const RtlFieldInfo * field)
{
jfieldID fieldId = getFieldId(field, "Ljava/lang/String;", "String");
size32_t numchars16;
rtlDataAttr unicode16;
rtlUtf8ToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
jstring value = JNIenv->NewString(unicode16.getustr(), numchars16);
checkException();
if (inSet)
JNIenv->SetObjectArrayElement((jobjectArray) row, idx, value);
else
JNIenv->SetObjectField(row, fieldId, value);
JNIenv->DeleteLocalRef(value);
checkException();
}
virtual bool processBeginSet(const RtlFieldInfo * field, unsigned numElems, bool isAll, const byte *data)
{
push();
idx = 0;
limit = numElems;
const char *javaTypeSignature = NULL;
bool processElements = false;
// row needs to be created as an array of <whatever>
if (isAll)
UNSUPPORTED("ALL sets");
const RtlTypeInfo *childType = field->type->queryChildType();
jobject newRow;
switch(childType->fieldType & RFTMkind)
{
case type_boolean:
newRow = JNIenv->NewBooleanArray(numElems);
JNIenv->SetBooleanArrayRegion((jbooleanArray) newRow, 0, numElems, (jboolean *) data);
javaTypeSignature = "[Z";
break;
case type_int:
if (childType->fieldType & RFTMunsigned)
UNSUPPORTED("unsigned integers");
switch (childType->length)
{
case 1:
newRow = JNIenv->NewByteArray(numElems);
JNIenv->SetByteArrayRegion((jbyteArray) newRow, 0, numElems, (jbyte *) data);
javaTypeSignature = "[B";
break;
case 2:
newRow = JNIenv->NewShortArray(numElems);
JNIenv->SetShortArrayRegion((jshortArray) newRow, 0, numElems, (jshort *) data);
javaTypeSignature = "[S";
break;
case 4:
newRow = JNIenv->NewIntArray(numElems);
JNIenv->SetIntArrayRegion((jintArray) newRow, 0, numElems, (jint *) data);
javaTypeSignature = "[I";
break;
case 8:
newRow = JNIenv->NewLongArray(numElems);
JNIenv->SetLongArrayRegion((jlongArray) newRow, 0, numElems, (jlong *) data);
javaTypeSignature = "[J";
break;
default:
UNSUPPORTED("non-standard integer sizes");
break;
}
break;
case type_real:
switch (childType->length)
{
case 4:
newRow = JNIenv->NewFloatArray(numElems);
JNIenv->SetFloatArrayRegion((jfloatArray) newRow, 0, numElems, (float *) data);
javaTypeSignature = "[F";
break;
case 8:
newRow = JNIenv->NewDoubleArray(numElems);
JNIenv->SetDoubleArrayRegion((jdoubleArray) newRow, 0, numElems, (double *) data);
javaTypeSignature = "[D";
break;
default:
throwUnexpected();
break;
}
break;
case type_string:
case type_varstring:
case type_unicode:
case type_utf8:
newRow = JNIenv->NewObjectArray(numElems, JNIenv->FindClass("java/lang/String"), NULL);
javaTypeSignature = "[Ljava/lang/String;";
processElements = true;
break;
case type_data:
newRow = JNIenv->NewObjectArray(numElems, JNIenv->FindClass("[B"), NULL);
javaTypeSignature = "[[B";
processElements = true;
break;
default:
throwUnexpected();
}
checkException();
jfieldID fieldId = getFieldId(field, javaTypeSignature, "Array");
JNIenv->SetObjectField(row, fieldId, newRow);
row = newRow;
inSet = true;
return processElements;
}
virtual bool processBeginDataset(const RtlFieldInfo * field, unsigned numRows)
{
push();
idxStack.append(idx);
idx = 0;
inDataSet = true;
// Create an empty array
jfieldID childId = getFieldId( field, NULL, "RECORD");
jobject newRow = NULL;
if (numRows)
{
jclass arrayClass = getClassForChild(childId);
jmethodID isArrayMethod = JNIenv->GetMethodID(JNIenv->GetObjectClass(arrayClass), "isArray", "()Z" );
checkException();
if (!JNIenv->CallBooleanMethod(arrayClass, isArrayMethod))
{
JNIenv->ExceptionClear();
VStringBuffer message("javaembed: Array expected for field %s", field->name);
rtlFail(0, message.str());
}
// Set up constructor etc for the child rows, so we don't do it per row
jmethodID getTypeMethod = JNIenv->GetMethodID(JNIenv->GetObjectClass(arrayClass), "getComponentType", "()Ljava/lang/Class;" );
checkException();
Class = (jclass) JNIenv->CallObjectMethod(arrayClass, getTypeMethod);
checkException();
setConstructor();
// Now we need to create the array
newRow = JNIenv->NewObjectArray(numRows, Class, NULL);
checkException();
}
JNIenv->SetObjectField(row, childId, newRow);
checkException();
row = newRow;
return true;
}
virtual bool processBeginRow(const RtlFieldInfo * field)
{
if (field == outerRow)
row = JNIenv->NewObject(Class, constructor);
else
{
push();
stack.append(constructor);
// Now we have to create the child object
jobject newRow = NULL;
if (inDataSet)
{
newRow = JNIenv->NewObject(Class, constructor);
checkException();
JNIenv->SetObjectArrayElement((jobjectArray) row, idx++, newRow);
}
else
{
// All this is done once per dataset in the nested dataset case. But for embedded record case we have to do it here
jfieldID childId = getFieldId( field, NULL, "RECORD");
Class = getClassForChild(childId);
setConstructor();
newRow = JNIenv->NewObject(Class, constructor);
checkException();
JNIenv->SetObjectField(row, childId, newRow);
}
row = newRow;
}
checkException();
return true;
}
virtual void processEndSet(const RtlFieldInfo * field)
{
JNIenv->DeleteLocalRef(row);
pop();
inSet = false;
}
virtual void processEndDataset(const RtlFieldInfo * field)
{
inDataSet = false;
idx = idxStack.popGet();
pop();
}
virtual void processEndRow(const RtlFieldInfo * field)
{
if (field != outerRow)