-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathJniReferences.cpp
607 lines (512 loc) · 25.7 KB
/
JniReferences.cpp
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
/*
*
* Copyright (c) 2021-2022 Project CHIP Authors
*
* 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 <cstring>
#include <jni.h>
#include <lib/support/CHIPJNIError.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/JniReferences.h>
#include <lib/support/JniTypeWrappers.h>
#include <string>
namespace chip {
void JniReferences::SetJavaVm(JavaVM * jvm, const char * clsType)
{
VerifyOrReturn(mJvm == nullptr, ChipLogError(Support, "JavaVM is already set"));
mJvm = jvm;
// Cache the classloader for CHIP Java classes. env->FindClass() can start in the system class loader if called from a different
// thread, meaning it won't find our Chip classes.
// https://developer.android.com/training/articles/perf-jni#faq_FindClass
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturn(env != nullptr, ChipLogError(Support, "env can not be nullptr"));
// Any chip.devicecontroller.* class will work here - just need something to call getClassLoader() on.
jclass chipClass = env->FindClass(clsType);
VerifyOrReturn(chipClass != nullptr, ChipLogError(Support, "clsType can not be found"));
jclass classClass = env->FindClass("java/lang/Class");
jclass classLoaderClass = env->FindClass("java/lang/ClassLoader");
jmethodID getClassLoaderMethod = env->GetMethodID(classClass, "getClassLoader", "()Ljava/lang/ClassLoader;");
CHIP_ERROR err = mClassLoader.Init(env->CallObjectMethod(chipClass, getClassLoaderMethod));
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to init mClassLoader"));
mFindClassMethod = env->GetMethodID(classLoaderClass, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
jclass listClass = nullptr;
jclass arrayListClass = nullptr;
jclass hashMapClass = nullptr;
err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/List", listClass);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to get local class ref for List"));
err = mListClass.Init(static_cast<jobject>(listClass));
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to init mListClass"));
err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/ArrayList", arrayListClass);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to get local class ref for ArrayList"));
err = mArrayListClass.Init(static_cast<jobject>(arrayListClass));
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to init mArrayListClass"));
err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/HashMap", hashMapClass);
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to get local class ref for HashMap"));
mHashMapClass.Init(static_cast<jobject>(hashMapClass));
VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Support, "fail to init mHashMapClass"));
}
JNIEnv * JniReferences::GetEnvForCurrentThread()
{
JNIEnv * env;
if (mJvm == nullptr)
{
ChipLogError(Support, "Missing Java VM");
return nullptr;
}
mJvm->GetEnv((void **) &env, JNI_VERSION_1_6);
if (env == nullptr)
{
jint error;
#ifdef __ANDROID__
error = mJvm->AttachCurrentThreadAsDaemon(&env, nullptr);
#else
error = mJvm->AttachCurrentThreadAsDaemon((void **) &env, nullptr);
#endif
if (error != JNI_OK)
{
ChipLogError(Support, "Failed to get JNIEnv for the current thread");
return nullptr;
}
}
return env;
}
CHIP_ERROR JniReferences::GetLocalClassRef(JNIEnv * env, const char * clsType, jclass & outCls)
{
jclass cls = nullptr;
VerifyOrReturnError(mClassLoader.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE);
// Try `j$/util/Optional` when enabling Java8.
if (strcmp(clsType, "java/util/Optional") == 0)
{
cls = env->FindClass("j$/util/Optional");
env->ExceptionClear();
}
if (cls == nullptr)
{
cls = env->FindClass(clsType);
env->ExceptionClear();
}
if (cls == nullptr)
{
// Try the cached classloader if FindClass() didn't work.
cls = static_cast<jclass>(env->CallObjectMethod(mClassLoader.ObjectRef(), mFindClassMethod, env->NewStringUTF(clsType)));
VerifyOrReturnError(cls != nullptr && env->ExceptionCheck() != JNI_TRUE, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
}
outCls = cls;
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::N2J_ByteArray(JNIEnv * env, const uint8_t * inArray, jsize inArrayLen, jbyteArray & outArray)
{
outArray = env->NewByteArray(inArrayLen);
VerifyOrReturnError(outArray != nullptr, CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(outArray, 0, inArrayLen, (jbyte *) inArray);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return CHIP_NO_ERROR;
}
static std::string StrReplaceAll(const std::string & source, const std::string & from, const std::string & to)
{
std::string newString = source;
size_t pos = 0;
while ((pos = newString.find(from, pos)) != std::string::npos)
{
newString.replace(pos, from.length(), to);
pos += to.length();
}
return newString;
}
CHIP_ERROR JniReferences::FindMethod(JNIEnv * env, jobject object, const char * methodName, const char * methodSignature,
jmethodID * methodId)
{
jclass javaClass = nullptr;
VerifyOrReturnError(env != nullptr && object != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
javaClass = env->GetObjectClass(object);
VerifyOrReturnError(javaClass != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
*methodId = env->GetMethodID(javaClass, methodName, methodSignature);
env->ExceptionClear();
if (*methodId != nullptr)
{
return CHIP_NO_ERROR;
}
std::string method_signature = methodSignature;
method_signature = StrReplaceAll(method_signature, "java/util/Optional", "j$/util/Optional");
*methodId = env->GetMethodID(javaClass, methodName, method_signature.data());
env->ExceptionClear();
if (*methodId == nullptr)
{
ChipLogError(Support, "methodId is null : %s, %s", methodName, methodSignature);
return CHIP_JNI_ERROR_METHOD_NOT_FOUND;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::FindMethod(JNIEnv * env, jclass javaClass, const char * methodName, const char * methodSignature,
jmethodID * methodId)
{
VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
VerifyOrReturnError(javaClass != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
*methodId = env->GetMethodID(javaClass, methodName, methodSignature);
env->ExceptionClear();
if (*methodId != nullptr)
{
return CHIP_NO_ERROR;
}
std::string method_signature = methodSignature;
method_signature = StrReplaceAll(method_signature, "java/util/Optional", "j$/util/Optional");
*methodId = env->GetMethodID(javaClass, methodName, method_signature.data());
env->ExceptionClear();
VerifyOrReturnError(*methodId != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
return CHIP_NO_ERROR;
}
void JniReferences::CallVoidInt(JNIEnv * env, jobject object, const char * methodName, jint argument)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jmethodID method;
err = JniReferences::FindMethod(env, object, methodName, "(I)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Support, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format());
}
env->ExceptionClear();
env->CallVoidMethod(object, method, argument);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void JniReferences::CallVoidLong(JNIEnv * env, jobject object, const char * methodName, jlong argument)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jmethodID method;
err = JniReferences::FindMethod(env, object, methodName, "(J)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Support, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format());
}
env->ExceptionClear();
env->CallVoidMethod(object, method, argument);
VerifyOrReturn(!env->ExceptionCheck(), env->ExceptionDescribe());
}
void JniReferences::ReportError(JNIEnv * env, CHIP_ERROR cbErr, const char * functName)
{
if (cbErr == CHIP_JNI_ERROR_EXCEPTION_THROWN)
{
ChipLogError(Support, "Java exception thrown in %s", StringOrNullMarker(functName));
env->ExceptionDescribe();
}
else
{
const char * errStr;
switch (cbErr.AsInteger())
{
case CHIP_JNI_ERROR_TYPE_NOT_FOUND.AsInteger():
errStr = "JNI type not found";
break;
case CHIP_JNI_ERROR_METHOD_NOT_FOUND.AsInteger():
errStr = "JNI method not found";
break;
case CHIP_JNI_ERROR_FIELD_NOT_FOUND.AsInteger():
errStr = "JNI field not found";
break;
default:
errStr = ErrorStr(cbErr);
break;
}
ChipLogError(Support, "Error in %s : %s", StringOrNullMarker(functName), errStr);
}
}
void JniReferences::ThrowError(JNIEnv * env, jclass exceptionCls, CHIP_ERROR errToThrow)
{
env->ExceptionClear();
jmethodID constructor = env->GetMethodID(exceptionCls, "<init>", "(JLjava/lang/String;)V");
VerifyOrReturn(constructor != nullptr);
jstring jerrStr = env->NewStringUTF(ErrorStr(errToThrow));
jthrowable outEx =
static_cast<jthrowable>(env->NewObject(exceptionCls, constructor, static_cast<jlong>(errToThrow.AsInteger()), jerrStr));
VerifyOrReturn(!env->ExceptionCheck());
env->Throw(outEx);
}
void JniReferences::ThrowError(JNIEnv * env, JniGlobalReference & exceptionCls, CHIP_ERROR errToThrow)
{
VerifyOrReturn(exceptionCls.HasValidObjectRef(), ChipLogError(Support, "exceptionCls is invalid, failed to throw error"));
ThrowError(env, static_cast<jclass>(exceptionCls.ObjectRef()), errToThrow);
}
CHIP_ERROR JniReferences::CreateOptional(jobject objectToWrap, jobject & outOptional)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
jclass optionalCls = nullptr;
ReturnErrorOnFailure(chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/util/Optional", optionalCls));
jmethodID ofMethod = env->GetStaticMethodID(optionalCls, "ofNullable", "(Ljava/lang/Object;)Ljava/util/Optional;");
env->ExceptionClear();
// Try `Lj$/util/Optional;` when enabling Java8.
if (ofMethod == nullptr)
{
ofMethod = env->GetStaticMethodID(optionalCls, "ofNullable", "(Ljava/lang/Object;)Lj$/util/Optional;");
env->ExceptionClear();
}
VerifyOrReturnError(ofMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
outOptional = env->CallStaticObjectMethod(optionalCls, ofMethod, objectToWrap);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::GetOptionalValue(jobject optionalObj, jobject & optionalValue)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
VerifyOrReturnError(optionalObj != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
jclass optionalCls = env->GetObjectClass(optionalObj);
jmethodID isPresentMethod = env->GetMethodID(optionalCls, "isPresent", "()Z");
VerifyOrReturnError(isPresentMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
jboolean isPresent = optionalObj && env->CallBooleanMethod(optionalObj, isPresentMethod);
if (!isPresent)
{
optionalValue = nullptr;
return CHIP_NO_ERROR;
}
jmethodID getMethod = env->GetMethodID(optionalCls, "get", "()Ljava/lang/Object;");
VerifyOrReturnError(getMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
optionalValue = env->CallObjectMethod(optionalObj, getMethod);
return CHIP_NO_ERROR;
}
jint JniReferences::IntegerToPrimitive(jobject boxedInteger)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr"));
jclass boxedTypeCls = nullptr;
CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Integer", boxedTypeCls);
VerifyOrReturnValue(err == CHIP_NO_ERROR, 0,
ChipLogError(Support, "IntegerToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format()));
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "intValue", "()I");
return env->CallIntMethod(boxedInteger, valueMethod);
}
jlong JniReferences::LongToPrimitive(jobject boxedLong)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr"));
jclass boxedTypeCls = nullptr;
CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Long", boxedTypeCls);
VerifyOrReturnValue(err == CHIP_NO_ERROR, 0,
ChipLogError(Support, "LongToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format()));
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "longValue", "()J");
return env->CallLongMethod(boxedLong, valueMethod);
}
jboolean JniReferences::BooleanToPrimitive(jobject boxedBoolean)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnValue(env != nullptr, false, ChipLogError(Support, "env cannot be nullptr"));
jclass boxedTypeCls = nullptr;
CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Boolean", boxedTypeCls);
VerifyOrReturnValue(err == CHIP_NO_ERROR, false,
ChipLogError(Support, "BooleanToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format()));
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "booleanValue", "()Z");
return env->CallBooleanMethod(boxedBoolean, valueMethod);
}
jfloat JniReferences::FloatToPrimitive(jobject boxedFloat)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr"));
jclass boxedTypeCls = nullptr;
CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Float", boxedTypeCls);
VerifyOrReturnValue(err == CHIP_NO_ERROR, 0,
ChipLogError(Support, "FloatToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format()));
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "floatValue", "()F");
return env->CallFloatMethod(boxedFloat, valueMethod);
}
jdouble JniReferences::DoubleToPrimitive(jobject boxedDouble)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr"));
jclass boxedTypeCls = nullptr;
CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Double", boxedTypeCls);
VerifyOrReturnValue(err == CHIP_NO_ERROR, 0,
ChipLogError(Support, "DoubleToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format()));
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "doubleValue", "()D");
return env->CallDoubleMethod(boxedDouble, valueMethod);
}
jshort JniReferences::ShortToPrimitive(jobject boxedShort)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnValue(env != nullptr, 0, ChipLogError(Support, "env cannot be nullptr"));
jclass boxedTypeCls = nullptr;
CHIP_ERROR err = chip::JniReferences::GetInstance().GetLocalClassRef(env, "java/lang/Short", boxedTypeCls);
VerifyOrReturnValue(err == CHIP_NO_ERROR, 0,
ChipLogError(Support, "ShortToPrimitive failed due to %" CHIP_ERROR_FORMAT, err.Format()));
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "shortValue", "()S");
return env->CallShortMethod(boxedShort, valueMethod);
}
CHIP_ERROR JniReferences::CallSubscriptionEstablished(jobject javaCallback, long subscriptionId)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
jmethodID subscriptionEstablishedMethod;
err = chip::JniReferences::GetInstance().FindMethod(env, javaCallback, "onSubscriptionEstablished", "(J)V",
&subscriptionEstablishedMethod);
VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
env->CallVoidMethod(javaCallback, subscriptionEstablishedMethod, static_cast<jlong>(subscriptionId));
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return err;
}
CHIP_ERROR JniReferences::CreateArrayList(jobject & outList)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mArrayListClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE);
jclass ref = static_cast<jclass>(mArrayListClass.ObjectRef());
jmethodID arrayListCtor = env->GetMethodID(ref, "<init>", "()V");
VerifyOrReturnError(arrayListCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
outList = env->NewObject(ref, arrayListCtor);
VerifyOrReturnError(outList != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::AddToList(jobject list, jobject objectToAdd)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mArrayListClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE);
jclass ref = static_cast<jclass>(mListClass.ObjectRef());
jmethodID addMethod = env->GetMethodID(ref, "add", "(Ljava/lang/Object;)Z");
VerifyOrReturnError(addMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
env->CallBooleanMethod(list, addMethod, objectToAdd);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::CreateHashMap(jobject & outMap)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mHashMapClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE);
jclass ref = static_cast<jclass>(mHashMapClass.ObjectRef());
jmethodID hashMapCtor = env->GetMethodID(ref, "<init>", "()V");
VerifyOrReturnError(hashMapCtor != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
outMap = env->NewObject(ref, hashMapCtor);
VerifyOrReturnError(outMap != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::PutInMap(jobject map, jobject key, jobject value)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mHashMapClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE);
jclass ref = static_cast<jclass>(mHashMapClass.ObjectRef());
jmethodID putMethod = env->GetMethodID(ref, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
VerifyOrReturnError(putMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
env->CallObjectMethod(map, putMethod, key, value);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::GetListSize(jobject list, jint & size)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mListClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE);
jclass ref = static_cast<jclass>(mListClass.ObjectRef());
jmethodID sizeMethod = env->GetMethodID(ref, "size", "()I");
VerifyOrReturnError(sizeMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
size = env->CallIntMethod(list, sizeMethod);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::GetListItem(jobject list, jint index, jobject & outItem)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mListClass.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE);
jclass ref = static_cast<jclass>(mListClass.ObjectRef());
jmethodID getMethod = env->GetMethodID(ref, "get", "(I)Ljava/lang/Object;");
VerifyOrReturnError(getMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
outItem = env->CallObjectMethod(list, getMethod, index);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::GetObjectField(jobject objectToRead, const char * name, const char * signature, jobject & outObject)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(objectToRead != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
jclass objClass = env->GetObjectClass(objectToRead);
jfieldID field = env->GetFieldID(objClass, name, signature);
outObject = env->GetObjectField(objectToRead, field);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::CharToStringUTF(const chip::CharSpan & charSpan, jobject & outStr)
{
JNIEnv * env = GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_ERROR_INCORRECT_STATE);
jobject jbyteBuffer = env->NewDirectByteBuffer((void *) charSpan.data(), static_cast<jlong>(charSpan.size()));
jclass charSetClass = env->FindClass("java/nio/charset/Charset");
jmethodID charsetForNameMethod =
env->GetStaticMethodID(charSetClass, "forName", "(Ljava/lang/String;)Ljava/nio/charset/Charset;");
jobject charsetObject = env->CallStaticObjectMethod(charSetClass, charsetForNameMethod, env->NewStringUTF("UTF-8"));
jclass charSetDocoderClass = env->FindClass("java/nio/charset/CharsetDecoder");
jmethodID newDocoderMethod = env->GetMethodID(charSetClass, "newDecoder", "()Ljava/nio/charset/CharsetDecoder;");
jobject decoderObject = env->CallObjectMethod(charsetObject, newDocoderMethod);
// Even though spec requires UTF-8 strings, we have seen instances in the field of certified devices sending
// invalid strings like "startup?" (0x73 0x74 0x61 0x72 0x74 0x75 0x70 <0x91>) and we want to actually
// be lenient on those rather than failing an entire decode (which may fail an entire report for one invalid string,
// like in a very common 'subscribe *')
//
// As a result call:
// onMalformedInput(CodingErrorAction.REPLACE)
// onUnmappableCharacter(CodingErrorAction.REPLACE)
jclass codingErrorActionClass = env->FindClass("java/nio/charset/CodingErrorAction");
jobject replaceAction = env->GetStaticObjectField(
codingErrorActionClass, env->GetStaticFieldID(codingErrorActionClass, "REPLACE", "Ljava/nio/charset/CodingErrorAction;"));
{
jmethodID onMalformedInput = env->GetMethodID(charSetDocoderClass, "onMalformedInput",
"(Ljava/nio/charset/CodingErrorAction;)Ljava/nio/charset/CharsetDecoder;");
decoderObject = env->CallObjectMethod(decoderObject, onMalformedInput, replaceAction);
}
{
jmethodID onUnmappableCharacter =
env->GetMethodID(charSetDocoderClass, "onUnmappableCharacter",
"(Ljava/nio/charset/CodingErrorAction;)Ljava/nio/charset/CharsetDecoder;");
decoderObject = env->CallObjectMethod(decoderObject, onUnmappableCharacter, replaceAction);
}
jmethodID charSetDecodeMethod = env->GetMethodID(charSetDocoderClass, "decode", "(Ljava/nio/ByteBuffer;)Ljava/nio/CharBuffer;");
jobject decodeObject = env->CallObjectMethod(decoderObject, charSetDecodeMethod, jbyteBuffer);
env->DeleteLocalRef(jbyteBuffer);
// If decode exception occur, outStr will be set null.
outStr = nullptr;
if (env->ExceptionCheck())
{
// If there is an exception, decode will not fail. Instead just
// an error will be reported.
ChipLogError(Support, "Exception encountered trying to decode a UTF string.");
env->ExceptionDescribe();
env->ExceptionClear();
return CHIP_JNI_ERROR_EXCEPTION_THROWN;
}
jclass charBufferClass = env->FindClass("java/nio/CharBuffer");
jmethodID charBufferToString = env->GetMethodID(charBufferClass, "toString", "()Ljava/lang/String;");
outStr = static_cast<jstring>(env->CallObjectMethod(decodeObject, charBufferToString));
return CHIP_NO_ERROR;
}
CHIP_ERROR JniGlobalReference::Init(jobject aObjectRef)
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
VerifyOrReturnError(aObjectRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
VerifyOrReturnError(mObjectRef == nullptr, CHIP_ERROR_INCORRECT_STATE);
mObjectRef = env->NewGlobalRef(aObjectRef);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
VerifyOrReturnError(mObjectRef != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
return CHIP_NO_ERROR;
}
void JniGlobalReference::Reset()
{
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
if (env != nullptr && mObjectRef != nullptr)
{
env->DeleteGlobalRef(mObjectRef);
mObjectRef = nullptr;
}
}
} // namespace chip