xref: /unit/src/java/nxt_jni_Thread.c (revision 977:4f9268f27b57)
1 
2 /*
3  * Copyright (C) NGINX, Inc.
4  */
5 
6 #include <nxt_unit.h>
7 #include <jni.h>
8 
9 #include "nxt_jni_Thread.h"
10 
11 
12 static jclass     nxt_java_Thread_class;
13 static jmethodID  nxt_java_Thread_currentThread;
14 static jmethodID  nxt_java_Thread_getContextClassLoader;
15 static jmethodID  nxt_java_Thread_setContextClassLoader;
16 
17 
18 int
nxt_java_initThread(JNIEnv * env)19 nxt_java_initThread(JNIEnv *env)
20 {
21     jclass  cls;
22 
23     cls = (*env)->FindClass(env, "java/lang/Thread");
24     if (cls == NULL) {
25         nxt_unit_warn(NULL, "java.lang.Thread not found");
26         return NXT_UNIT_ERROR;
27     }
28 
29     nxt_java_Thread_class = (*env)->NewGlobalRef(env, cls);
30     (*env)->DeleteLocalRef(env, cls);
31     cls = nxt_java_Thread_class;
32 
33     nxt_java_Thread_currentThread = (*env)->GetStaticMethodID(env, cls,
34         "currentThread", "()Ljava/lang/Thread;");
35     if (nxt_java_Thread_currentThread == NULL) {
36         nxt_unit_warn(NULL, "java.lang.Thread.currentThread() not found");
37         goto failed;
38     }
39 
40     nxt_java_Thread_getContextClassLoader = (*env)->GetMethodID(env, cls,
41         "getContextClassLoader", "()Ljava/lang/ClassLoader;");
42     if (nxt_java_Thread_getContextClassLoader == NULL) {
43         nxt_unit_warn(NULL, "java.lang.Thread.getContextClassLoader() "
44                       "not found");
45         goto failed;
46     }
47 
48     nxt_java_Thread_setContextClassLoader = (*env)->GetMethodID(env, cls,
49         "setContextClassLoader", "(Ljava/lang/ClassLoader;)V");
50     if (nxt_java_Thread_setContextClassLoader == NULL) {
51         nxt_unit_warn(NULL, "java.lang.Thread.setContextClassLoader() "
52                       "not found");
53         goto failed;
54     }
55 
56     return NXT_UNIT_OK;
57 
58 failed:
59 
60     (*env)->DeleteGlobalRef(env, cls);
61     return NXT_UNIT_ERROR;
62 }
63 
64 void
nxt_java_setContextClassLoader(JNIEnv * env,jobject cl)65 nxt_java_setContextClassLoader(JNIEnv *env, jobject cl)
66 {
67     jobject thread;
68 
69     thread = (*env)->CallStaticObjectMethod(env, nxt_java_Thread_class,
70                                             nxt_java_Thread_currentThread);
71 
72     if (thread == NULL) {
73         return;
74     }
75 
76     (*env)->CallVoidMethod(env, thread, nxt_java_Thread_setContextClassLoader,
77                            cl);
78 }
79 
80 jobject
nxt_java_getContextClassLoader(JNIEnv * env)81 nxt_java_getContextClassLoader(JNIEnv *env)
82 {
83     jobject thread;
84 
85     thread = (*env)->CallStaticObjectMethod(env, nxt_java_Thread_class,
86                                             nxt_java_Thread_currentThread);
87 
88     if (thread == NULL) {
89         return NULL;
90     }
91 
92     return (*env)->CallObjectMethod(env, thread,
93                                     nxt_java_Thread_getContextClassLoader);
94 }
95