blob: 330732c8bb0635257f919c52821bb8fc9b56035b [file] [log] [blame]
Tony Mak6c4cc672018-09-17 11:48:50 +01001/*
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
28using libtextclassifier3::JStringToUtf8String;
29using libtextclassifier3::ScopedLocalRef;
30
31namespace libtextclassifier3 {
32
33std::string ToStlString(JNIEnv* env, const jstring& str) {
34 std::string result;
35 JStringToUtf8String(env, str, &result);
36 return result;
37}
38
Tony Mak51a9e542018-11-02 13:36:22 +000039jint GetFdFromFileDescriptor(JNIEnv* env, jobject fd) {
Tony Mak6c4cc672018-09-17 11:48:50 +010040 ScopedLocalRef<jclass> fd_class(env->FindClass("java/io/FileDescriptor"),
41 env);
42 if (fd_class == nullptr) {
43 TC3_LOG(ERROR) << "Couldn't find FileDescriptor.";
44 return reinterpret_cast<jlong>(nullptr);
45 }
46 jfieldID fd_class_descriptor =
47 env->GetFieldID(fd_class.get(), "descriptor", "I");
48 if (fd_class_descriptor == nullptr) {
49 TC3_LOG(ERROR) << "Couldn't find descriptor.";
50 return reinterpret_cast<jlong>(nullptr);
51 }
Tony Mak51a9e542018-11-02 13:36:22 +000052 return env->GetIntField(fd, fd_class_descriptor);
53}
Tony Mak6c4cc672018-09-17 11:48:50 +010054
Tony Mak51a9e542018-11-02 13:36:22 +000055jint GetFdFromAssetFileDescriptor(JNIEnv* env, jobject afd) {
56 ScopedLocalRef<jclass> afd_class(
57 env->FindClass("android/content/res/AssetFileDescriptor"), env);
58 if (afd_class == nullptr) {
59 TC3_LOG(ERROR) << "Couldn't find AssetFileDescriptor.";
60 return reinterpret_cast<jlong>(nullptr);
61 }
62 jmethodID afd_class_getFileDescriptor = env->GetMethodID(
63 afd_class.get(), "getFileDescriptor", "()Ljava/io/FileDescriptor;");
64 if (afd_class_getFileDescriptor == nullptr) {
65 TC3_LOG(ERROR) << "Couldn't find getFileDescriptor.";
66 return reinterpret_cast<jlong>(nullptr);
67 }
Tony Mak6c4cc672018-09-17 11:48:50 +010068 jobject bundle_jfd = env->CallObjectMethod(afd, afd_class_getFileDescriptor);
Tony Mak51a9e542018-11-02 13:36:22 +000069 return GetFdFromFileDescriptor(env, bundle_jfd);
Tony Mak6c4cc672018-09-17 11:48:50 +010070}
71
72} // namespace libtextclassifier3