blob: ef865a891a0a82eac0a725964d352821cf720345 [file] [log] [blame]
Lukas Zilkab23e2122018-02-09 10:25:19 +01001/*
Tony Mak6c4cc672018-09-17 11:48:50 +01002 * Copyright (C) 2018 The Android Open Source Project
Lukas Zilkab23e2122018-02-09 10:25:19 +01003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Tony Mak6c4cc672018-09-17 11:48:50 +010017#include "utils/java/string_utils.h"
Lukas Zilkab23e2122018-02-09 10:25:19 +010018
Tony Mak6c4cc672018-09-17 11:48:50 +010019#include "utils/base/logging.h"
Lukas Zilkab23e2122018-02-09 10:25:19 +010020
Tony Mak6c4cc672018-09-17 11:48:50 +010021namespace libtextclassifier3 {
Lukas Zilkab23e2122018-02-09 10:25:19 +010022
Tony Mak51a9e542018-11-02 13:36:22 +000023bool JByteArrayToString(JNIEnv* env, const jbyteArray& array,
24 std::string* result) {
25 jbyte* const array_bytes = env->GetByteArrayElements(array, JNI_FALSE);
26 if (array_bytes == nullptr) {
27 return false;
28 }
29
30 const int array_length = env->GetArrayLength(array);
31 *result = std::string(reinterpret_cast<char*>(array_bytes), array_length);
32
33 env->ReleaseByteArrayElements(array, array_bytes, JNI_ABORT);
34
35 return true;
36}
37
Lukas Zilkab23e2122018-02-09 10:25:19 +010038bool JStringToUtf8String(JNIEnv* env, const jstring& jstr,
39 std::string* result) {
40 if (jstr == nullptr) {
41 *result = std::string();
42 return false;
43 }
44
45 jclass string_class = env->FindClass("java/lang/String");
46 if (!string_class) {
Tony Mak6c4cc672018-09-17 11:48:50 +010047 TC3_LOG(ERROR) << "Can't find String class";
Lukas Zilkab23e2122018-02-09 10:25:19 +010048 return false;
49 }
50
51 jmethodID get_bytes_id =
52 env->GetMethodID(string_class, "getBytes", "(Ljava/lang/String;)[B");
53
54 jstring encoding = env->NewStringUTF("UTF-8");
Tony Mak51a9e542018-11-02 13:36:22 +000055
Lukas Zilkab23e2122018-02-09 10:25:19 +010056 jbyteArray array = reinterpret_cast<jbyteArray>(
57 env->CallObjectMethod(jstr, get_bytes_id, encoding));
58
Tony Mak51a9e542018-11-02 13:36:22 +000059 JByteArrayToString(env, array, result);
Lukas Zilkab23e2122018-02-09 10:25:19 +010060
61 // Release the array.
Lukas Zilkab23e2122018-02-09 10:25:19 +010062 env->DeleteLocalRef(array);
63 env->DeleteLocalRef(string_class);
64 env->DeleteLocalRef(encoding);
65
66 return true;
67}
68
Tony Mak6c4cc672018-09-17 11:48:50 +010069} // namespace libtextclassifier3