Home | History | Annotate | Download | only in java
      1 /*
      2  * Copyright (C) 2017 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 "util/java/string_utils.h"
     18 
     19 #include "util/base/logging.h"
     20 
     21 namespace libtextclassifier2 {
     22 
     23 bool 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) {
     32     TC_LOG(ERROR) << "Can't find String class";
     33     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 
     57 }  // namespace libtextclassifier2
     58