aboutsummaryrefslogtreecommitdiffstats
path: root/java/jni/helper_base.cxx
blob: c72de97f728efe9617f010a6fbb203e220f69de2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
 * Author: Andrei Vasiliu <andrei.vasiliu@intel.com>
 * Copyright (c) 2016 Intel Corporation.
 *
 * Author: Sven Gothel <sgothel@jausoft.com>
 * Copyright (c) 2020 Gothel Software e.K.
 * Copyright (c) 2020 ZAFENA AB
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <jni.h>
#include <memory>
#include <stdexcept>
#include <vector>

#define VERBOSE_ON 1
#include <dbt_debug.hpp>

#include "helper_base.hpp"

#define JAVA_MAIN_PACKAGE "org/tinyb"

jfieldID getInstanceField(JNIEnv *env, jobject obj)
{
    jclass clazz = env->GetObjectClass(obj);
    // J == long
    return env->GetFieldID(clazz, "nativeInstance", "J");
}

jclass search_class(JNIEnv *env, const char *clazz_name)
{
    jclass clazz = env->FindClass(clazz_name);
    if (!clazz)
    {
        std::string error = "no class found: "; error += clazz_name;
        throw std::runtime_error(error);
    }
    return clazz;
}

jclass search_class(JNIEnv *env, jobject obj)
{
    jclass clazz = env->GetObjectClass(obj);
    if (!clazz)
    {
        std::string error = "no class found: ";
        throw std::runtime_error(error);
    }
    return clazz;
}

jmethodID search_method(JNIEnv *env, jclass clazz, const char *method_name,
                const char *prototype, bool is_static)
{
    jmethodID method;
    if (is_static)
    {
        method = env->GetStaticMethodID(clazz, method_name, prototype);
    }
    else
    {
        method = env->GetMethodID(clazz, method_name, prototype);
    }

    if (!method)
    {
        throw std::runtime_error("no method found\n");
    }

    return method;
}

jfieldID search_field(JNIEnv *env, jclass clazz, const char *field_name,
                const char *type, bool is_static)
{
    jfieldID field;
    if (is_static)
    {
        field = env->GetStaticFieldID(clazz, field_name, type);
    }
    else
    {
        field = env->GetFieldID(clazz, field_name, type);
    }

    if (!field)
    {
        throw std::runtime_error("no method found\n");
    }

    return field;
}

bool from_jboolean_to_bool(jboolean val)
{
    bool result;

    if (val == JNI_TRUE)
    {
        result = true;
    }
    else
    {
        if (val == JNI_FALSE)
        {
            result = false;
        }
        else
        {
            throw std::invalid_argument("the jboolean value is not true/false\n");
        }
    }

    return result;
}

std::string from_jstring_to_string(JNIEnv *env, jstring str)
{
    jboolean is_copy = JNI_TRUE;
    if (!str) {
        throw std::invalid_argument("String should not be null");
    }
    const char *str_chars = (char *)env->GetStringUTFChars(str, &is_copy);
    if (!str_chars) {
        throw std::bad_alloc();
    }
    const std::string string_to_write = std::string(str_chars);

    env->ReleaseStringUTFChars(str, str_chars);

    return string_to_write;
}

jstring from_string_to_jstring(JNIEnv *env, const std::string & str)
{
    return env->NewStringUTF(str.c_str());
}

jobject get_bluetooth_type(JNIEnv *env, const char *field_name)
{
    jclass b_type_enum = search_class(env, JAVA_MAIN_PACKAGE "/BluetoothType");

    jfieldID b_type_field = search_field(env, b_type_enum, field_name, "L" JAVA_MAIN_PACKAGE "/BluetoothType;", true);

    jobject result = env->GetStaticObjectField(b_type_enum, b_type_field);
    env->DeleteLocalRef(b_type_enum);
    return result;
}

jobject get_new_arraylist(JNIEnv *env, unsigned int size, jmethodID *add)
{
    jclass arraylist_class = search_class(env, "Ljava/util/ArrayList;");
    jmethodID arraylist_ctor = search_method(env, arraylist_class, "<init>", "(I)V", false);

    jobject result = env->NewObject(arraylist_class, arraylist_ctor, size);
    if (!result)
    {
        throw std::runtime_error("cannot create instance of class\n");
    }

    *add = search_method(env, arraylist_class, "add", "(Ljava/lang/Object;)Z", false);

    env->DeleteLocalRef(arraylist_class);
    return result;
}

void raise_java_exception(JNIEnv *env, std::exception &e)
{
    env->ThrowNew(env->FindClass("java/lang/Error"), e.what());
}

void raise_java_runtime_exception(JNIEnv *env, std::runtime_error &e)
{
    env->ThrowNew(env->FindClass("java/lang/RuntimeException"), e.what());
}

void raise_java_runtime_exception(JNIEnv *env, direct_bt::RuntimeException &e) {
    env->ThrowNew(env->FindClass("java/lang/RuntimeException"), e.what());
}

void raise_java_oom_exception(JNIEnv *env, std::bad_alloc &e)
{
    env->ThrowNew(env->FindClass("java/lang/OutOfMemoryException"), e.what());
}

void raise_java_invalid_arg_exception(JNIEnv *env, std::invalid_argument &e)
{
    env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), e.what());
}

void raise_java_bluetooth_exception(JNIEnv *env, direct_bt::BluetoothException &e)
{
    env->ThrowNew(env->FindClass("org/tinyb/BluetoothException"), e.what());
}

void rethrow_and_raise_java_exception(JNIEnv *env) {
    // std::exception_ptr e = std::current_exception();
    try {
        // std::rethrow_exception(e);
        throw; // re-throw current exception
    } catch (std::bad_alloc &e) { \
        raise_java_oom_exception(env, e);
    } catch (direct_bt::BluetoothException &e) {
        raise_java_bluetooth_exception(env, e);
    } catch (direct_bt::RuntimeException &e) {
        raise_java_runtime_exception(env, e);
    } catch (std::runtime_error &e) {
        raise_java_runtime_exception(env, e);
    } catch (std::invalid_argument &e) {
        raise_java_invalid_arg_exception(env, e);
    } catch (std::exception &e) {
        raise_java_exception(env, e);
    } catch (std::string &msg) {
        env->ThrowNew(env->FindClass("java/lang/Error"), msg.c_str());
    } catch (const char *msg) {
        env->ThrowNew(env->FindClass("java/lang/Error"), msg);
    } catch (...) {
        env->ThrowNew(env->FindClass("java/lang/Error"), "Unknown exception type");
    }
}

bool java_exception_check(JNIEnv *env, const char* file, int line)
{
    jthrowable e = env->ExceptionOccurred();
    if( nullptr != e ) {
#ifdef VERBOSE_ON
        DBG_PRINT("Java exception occurred @ %s : %d and forwarded.", file, line);
        // ExceptionDescribe prints an exception and a backtrace of the stack to a system error-reporting channel, such as stderr.
        // The pending exception is cleared as a side-effect of calling this function. This is a convenience routine provided for debugging.
        env->ExceptionDescribe();
#endif /* VERBOSE_ON */
        env->ExceptionClear(); // just be sure, to have same side-effects
        env->Throw(e); // re-throw the java exception - java side!
        return true;
    }
    return false;
}

void java_exception_check_and_throw(JNIEnv *env, const char* file, int line)
{
    jthrowable e = env->ExceptionOccurred();
    if( nullptr != e ) {
        ERR_PRINT("Java exception occurred @ %s : %d and forwarded.", file, line);
        // ExceptionDescribe prints an exception and a backtrace of the stack to a system error-reporting channel, such as stderr.
        // The pending exception is cleared as a side-effect of calling this function. This is a convenience routine provided for debugging.
        env->ExceptionDescribe();
        env->ExceptionClear(); // just be sure, to have same side-effects

        jclass eClazz = search_class(env, e);
        jmethodID toString = search_method(env, eClazz, "toString", "()Ljava/lang/String;", false);
        jstring jmsg = (jstring) env->CallObjectMethod(e, toString);
        std::string msg = from_jstring_to_string(env, jmsg);
        throw direct_bt::RuntimeException("Java exception occurred @ %s : %d: "+msg, file, line);
    }
}