summaryrefslogtreecommitdiffhomepage
path: root/src/java/nxt_jni_Thread.c
blob: 43dd90bdd387a9677de02d2d1ef0784131b9a579 (plain) (blame)
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

/*
 * Copyright (C) NGINX, Inc.
 */

#include <nxt_unit.h>
#include <jni.h>

#include "nxt_jni_Thread.h"


static jclass     nxt_java_Thread_class;
static jmethodID  nxt_java_Thread_currentThread;
static jmethodID  nxt_java_Thread_getContextClassLoader;
static jmethodID  nxt_java_Thread_setContextClassLoader;


int
nxt_java_initThread(JNIEnv *env)
{
    jclass  cls;

    cls = (*env)->FindClass(env, "java/lang/Thread");
    if (cls == NULL) {
        nxt_unit_warn(NULL, "java.lang.Thread not found");
        return NXT_UNIT_ERROR;
    }

    nxt_java_Thread_class = (*env)->NewGlobalRef(env, cls);
    (*env)->DeleteLocalRef(env, cls);
    cls = nxt_java_Thread_class;

    nxt_java_Thread_currentThread = (*env)->GetStaticMethodID(env, cls,
        "currentThread", "()Ljava/lang/Thread;");
    if (nxt_java_Thread_currentThread == NULL) {
        nxt_unit_warn(NULL, "java.lang.Thread.currentThread() not found");
        goto failed;
    }

    nxt_java_Thread_getContextClassLoader = (*env)->GetMethodID(env, cls,
        "getContextClassLoader", "()Ljava/lang/ClassLoader;");
    if (nxt_java_Thread_getContextClassLoader == NULL) {
        nxt_unit_warn(NULL, "java.lang.Thread.getContextClassLoader() "
                      "not found");
        goto failed;
    }

    nxt_java_Thread_setContextClassLoader = (*env)->GetMethodID(env, cls,
        "setContextClassLoader", "(Ljava/lang/ClassLoader;)V");
    if (nxt_java_Thread_setContextClassLoader == NULL) {
        nxt_unit_warn(NULL, "java.lang.Thread.setContextClassLoader() "
                      "not found");
        goto failed;
    }

    return NXT_UNIT_OK;

failed:

    (*env)->DeleteGlobalRef(env, cls);
    return NXT_UNIT_ERROR;
}

void
nxt_java_setContextClassLoader(JNIEnv *env, jobject cl)
{
    jobject thread;

    thread = (*env)->CallStaticObjectMethod(env, nxt_java_Thread_class,
                                            nxt_java_Thread_currentThread);

    if (thread == NULL) {
        return;
    }

    (*env)->CallVoidMethod(env, thread, nxt_java_Thread_setContextClassLoader,
                           cl);
}

jobject
nxt_java_getContextClassLoader(JNIEnv *env)
{
    jobject thread;

    thread = (*env)->CallStaticObjectMethod(env, nxt_java_Thread_class,
                                            nxt_java_Thread_currentThread);

    if (thread == NULL) {
        return NULL;
    }

    return (*env)->CallObjectMethod(env, thread,
                                    nxt_java_Thread_getContextClassLoader);
}