1 //  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 //
6 // This file implements the callback "bridge" between Java and C++ for
7 // ROCKSDB_NAMESPACE::TableFilter.
8 
9 #include "rocksjni/table_filter_jnicallback.h"
10 #include "rocksjni/portal.h"
11 
12 namespace ROCKSDB_NAMESPACE {
TableFilterJniCallback(JNIEnv * env,jobject jtable_filter)13 TableFilterJniCallback::TableFilterJniCallback(
14     JNIEnv* env, jobject jtable_filter)
15     : JniCallback(env, jtable_filter) {
16   m_jfilter_methodid =
17       AbstractTableFilterJni::getFilterMethod(env);
18   if(m_jfilter_methodid == nullptr) {
19     // exception thrown: NoSuchMethodException or OutOfMemoryError
20     return;
21   }
22 
23   // create the function reference
24   /*
25   Note the JNI ENV must be obtained/release
26   on each call to the function itself as
27   it may be called from multiple threads
28   */
29   m_table_filter_function =
30       [this](const ROCKSDB_NAMESPACE::TableProperties& table_properties) {
31         jboolean attached_thread = JNI_FALSE;
32         JNIEnv* thread_env = getJniEnv(&attached_thread);
33         assert(thread_env != nullptr);
34 
35         // create a Java TableProperties object
36         jobject jtable_properties = TablePropertiesJni::fromCppTableProperties(
37             thread_env, table_properties);
38         if (jtable_properties == nullptr) {
39           // exception thrown from fromCppTableProperties
40           thread_env->ExceptionDescribe();  // print out exception to stderr
41           releaseJniEnv(attached_thread);
42           return false;
43         }
44 
45         jboolean result = thread_env->CallBooleanMethod(
46             m_jcallback_obj, m_jfilter_methodid, jtable_properties);
47         if (thread_env->ExceptionCheck()) {
48           // exception thrown from CallBooleanMethod
49           thread_env->DeleteLocalRef(jtable_properties);
50           thread_env->ExceptionDescribe();  // print out exception to stderr
51           releaseJniEnv(attached_thread);
52           return false;
53         }
54 
55         // ok... cleanup and then return
56         releaseJniEnv(attached_thread);
57         return static_cast<bool>(result);
58       };
59 }
60 
61 std::function<bool(const ROCKSDB_NAMESPACE::TableProperties&)>
GetTableFilterFunction()62 TableFilterJniCallback::GetTableFilterFunction() {
63   return m_table_filter_function;
64 }
65 
66 }  // namespace ROCKSDB_NAMESPACE
67