• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
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 
17 #include "utils/java/string_utils.h"
18 
19 #include "utils/base/logging.h"
20 
21 namespace libtextclassifier3 {
22 
JByteArrayToString(JNIEnv * env,const jbyteArray & array,std::string * result)23 bool 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 
JStringToUtf8String(JNIEnv * env,const jstring & jstr,std::string * result)38 bool 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) {
47     TC3_LOG(ERROR) << "Can't find String class";
48     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");
55 
56   jbyteArray array = reinterpret_cast<jbyteArray>(
57       env->CallObjectMethod(jstr, get_bytes_id, encoding));
58 
59   JByteArrayToString(env, array, result);
60 
61   // Release the array.
62   env->DeleteLocalRef(array);
63   env->DeleteLocalRef(string_class);
64   env->DeleteLocalRef(encoding);
65 
66   return true;
67 }
68 
GetScopedStringChars(JNIEnv * env,jstring string,jboolean * is_copy)69 ScopedStringChars GetScopedStringChars(JNIEnv* env, jstring string,
70                                        jboolean* is_copy) {
71   return ScopedStringChars(env->GetStringUTFChars(string, is_copy),
72                            StringCharsReleaser(env, string));
73 }
74 
75 }  // namespace libtextclassifier3
76