1 /*
2  * Copyright (C) 2023 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 /* Header for class com_android_adservices_ActJni */
17 
18 #include <jni.h>
19 #include <google/protobuf/message_lite.h>
20 
21 #ifndef ADSERVICES_SERVICE_CORE_JNI_INCLUDE_JNI_UTIL_H_
22 #define ADSERVICES_SERVICE_CORE_JNI_INCLUDE_JNI_UTIL_H_
23 
24 namespace jni_util {
25 
26 class JniUtil {
27     public:
ThrowJavaException(JNIEnv * env,const char * exception_class_name,const char * message)28         static void ThrowJavaException(JNIEnv* env, const char* exception_class_name,
29                                                         const char* message) {
30             env->ThrowNew(env->FindClass(exception_class_name), message);
31 
32         }
33 
BytesToCppProto(JNIEnv * env,google::protobuf::MessageLite * proto,jbyteArray input)34         static bool BytesToCppProto(JNIEnv* env, google::protobuf::MessageLite* proto,
35                                                                             jbyteArray input) {
36             bool parsed_ok = false;
37             const int size = env->GetArrayLength(input);
38             void* ptr = env->GetPrimitiveArrayCritical(input, nullptr);
39             if (ptr) {
40                 parsed_ok = proto->ParseFromArray(static_cast<char*>(ptr), size);
41                 env->ReleasePrimitiveArrayCritical(input, ptr, JNI_ABORT);
42             }
43             return parsed_ok;
44         }
45 
SerializeProtoToJniByteArray(JNIEnv * env,const google::protobuf::MessageLite & protobuf)46         static jbyteArray SerializeProtoToJniByteArray(JNIEnv* env,
47                                                    const google::protobuf::MessageLite& protobuf) {
48            const int size = protobuf.ByteSizeLong();
49            jbyteArray ret = env->NewByteArray(size);
50            if (ret == nullptr) {
51                return nullptr;
52            }
53 
54            uint8_t* scoped_array
55                             = static_cast<uint8_t* >(env->GetPrimitiveArrayCritical(ret, nullptr));
56            protobuf.SerializeWithCachedSizesToArray(scoped_array);
57            env->ReleasePrimitiveArrayCritical(ret, scoped_array, 0);
58            return ret;
59        }
60 };
61 
62 }
63 
64 #endif //ADSERVICES_SERVICE_CORE_JNI_INCLUDE_JNI_UTIL_H_
65