1 // Copyright 2022, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Contains a structure defining the JNI context with frequently used helper methods.
16 use jni::objects::{JList, JObject};
17 use jni::JNIEnv;
18 
19 /// Struct containing the JNI environment and a java object. It contains methods
20 /// that work on the java object using the JNI environment
21 #[derive(Copy, Clone)]
22 pub struct JniContext<'a> {
23     pub env: JNIEnv<'a>,
24     pub obj: JObject<'a>,
25 }
26 
27 impl<'a> JniContext<'a> {
new(env: JNIEnv<'a>, obj: JObject<'a>) -> Self28     pub fn new(env: JNIEnv<'a>, obj: JObject<'a>) -> Self {
29         Self { env, obj }
30     }
31 
int_getter(&self, method: &str) -> Result<i32, jni::errors::Error>32     pub fn int_getter(&self, method: &str) -> Result<i32, jni::errors::Error> {
33         self.env.call_method(self.obj, method, "()I", &[])?.i()
34     }
35 
long_getter(&self, method: &str) -> Result<i64, jni::errors::Error>36     pub fn long_getter(&self, method: &str) -> Result<i64, jni::errors::Error> {
37         self.env.call_method(self.obj, method, "()J", &[])?.j()
38     }
39 
bool_getter(&self, method: &str) -> Result<bool, jni::errors::Error>40     pub fn bool_getter(&self, method: &str) -> Result<bool, jni::errors::Error> {
41         self.env.call_method(self.obj, method, "()Z", &[])?.z()
42     }
43 
byte_arr_getter(&self, method: &str) -> Result<Vec<u8>, jni::errors::Error>44     pub fn byte_arr_getter(&self, method: &str) -> Result<Vec<u8>, jni::errors::Error> {
45         let val_obj = self.env.call_method(self.obj, method, "()[B", &[])?.l()?;
46         self.env.convert_byte_array(val_obj.into_raw())
47     }
48 
object_getter( &'a self, method: &str, class: &str, ) -> Result<JObject<'a>, jni::errors::Error>49     pub fn object_getter(
50         &'a self,
51         method: &str,
52         class: &str,
53     ) -> Result<JObject<'a>, jni::errors::Error> {
54         self.env.call_method(self.obj, method, class, &[])?.l()
55     }
56 
list_getter(&'a self, method: &str) -> Result<JList<'a, 'a>, jni::errors::Error>57     pub fn list_getter(&'a self, method: &str) -> Result<JList<'a, 'a>, jni::errors::Error> {
58         let list_obj = self.env.call_method(self.obj, method, "()Ljava/util/List;", &[])?.l()?;
59         JList::from_env(&self.env, list_obj)
60     }
61 }
62