Tony Mak | 6c4cc67 | 2018-09-17 11:48:50 +0100 | [diff] [blame^] | 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/jni-base.h" |
| 18 | |
| 19 | #include <jni.h> |
| 20 | #include <type_traits> |
| 21 | #include <vector> |
| 22 | |
| 23 | #include "utils/base/integral_types.h" |
| 24 | #include "utils/java/scoped_local_ref.h" |
| 25 | #include "utils/java/string_utils.h" |
| 26 | #include "utils/memory/mmap.h" |
| 27 | |
| 28 | using libtextclassifier3::JStringToUtf8String; |
| 29 | using libtextclassifier3::ScopedLocalRef; |
| 30 | |
| 31 | namespace libtextclassifier3 { |
| 32 | |
| 33 | std::string ToStlString(JNIEnv* env, const jstring& str) { |
| 34 | std::string result; |
| 35 | JStringToUtf8String(env, str, &result); |
| 36 | return result; |
| 37 | } |
| 38 | |
| 39 | jint GetFdFromAssetFileDescriptor(JNIEnv* env, jobject afd) { |
| 40 | // Get system-level file descriptor from AssetFileDescriptor. |
| 41 | ScopedLocalRef<jclass> afd_class( |
| 42 | env->FindClass("android/content/res/AssetFileDescriptor"), env); |
| 43 | if (afd_class == nullptr) { |
| 44 | TC3_LOG(ERROR) << "Couldn't find AssetFileDescriptor."; |
| 45 | return reinterpret_cast<jlong>(nullptr); |
| 46 | } |
| 47 | jmethodID afd_class_getFileDescriptor = env->GetMethodID( |
| 48 | afd_class.get(), "getFileDescriptor", "()Ljava/io/FileDescriptor;"); |
| 49 | if (afd_class_getFileDescriptor == nullptr) { |
| 50 | TC3_LOG(ERROR) << "Couldn't find getFileDescriptor."; |
| 51 | return reinterpret_cast<jlong>(nullptr); |
| 52 | } |
| 53 | |
| 54 | ScopedLocalRef<jclass> fd_class(env->FindClass("java/io/FileDescriptor"), |
| 55 | env); |
| 56 | if (fd_class == nullptr) { |
| 57 | TC3_LOG(ERROR) << "Couldn't find FileDescriptor."; |
| 58 | return reinterpret_cast<jlong>(nullptr); |
| 59 | } |
| 60 | jfieldID fd_class_descriptor = |
| 61 | env->GetFieldID(fd_class.get(), "descriptor", "I"); |
| 62 | if (fd_class_descriptor == nullptr) { |
| 63 | TC3_LOG(ERROR) << "Couldn't find descriptor."; |
| 64 | return reinterpret_cast<jlong>(nullptr); |
| 65 | } |
| 66 | |
| 67 | jobject bundle_jfd = env->CallObjectMethod(afd, afd_class_getFileDescriptor); |
| 68 | return env->GetIntField(bundle_jfd, fd_class_descriptor); |
| 69 | } |
| 70 | |
| 71 | } // namespace libtextclassifier3 |