blob: 6d4a5d707174ff6459687184b8f58de6dbc4fe58 [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
23bool JStringToUtf8String(JNIEnv* env, const jstring& jstr,
24 std::string* result) {
25 if (jstr == nullptr) {
26 *result = std::string();
27 return false;
28 }
29
30 jclass string_class = env->FindClass("java/lang/String");
31 if (!string_class) {
Tony Mak6c4cc672018-09-17 11:48:50 +010032 TC3_LOG(ERROR) << "Can't find String class";
Lukas Zilkab23e2122018-02-09 10:25:19 +010033 return false;
34 }
35
36 jmethodID get_bytes_id =
37 env->GetMethodID(string_class, "getBytes", "(Ljava/lang/String;)[B");
38
39 jstring encoding = env->NewStringUTF("UTF-8");
40 jbyteArray array = reinterpret_cast<jbyteArray>(
41 env->CallObjectMethod(jstr, get_bytes_id, encoding));
42
43 jbyte* const array_bytes = env->GetByteArrayElements(array, JNI_FALSE);
44 int length = env->GetArrayLength(array);
45
46 *result = std::string(reinterpret_cast<char*>(array_bytes), length);
47
48 // Release the array.
49 env->ReleaseByteArrayElements(array, array_bytes, JNI_ABORT);
50 env->DeleteLocalRef(array);
51 env->DeleteLocalRef(string_class);
52 env->DeleteLocalRef(encoding);
53
54 return true;
55}
56
Tony Mak6c4cc672018-09-17 11:48:50 +010057} // namespace libtextclassifier3