2 * //******************************************************************
4 * // Copyright 2015 Intel Corporation.
6 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
8 * // Licensed under the Apache License, Version 2.0 (the "License");
9 * // you may not use this file except in compliance with the License.
10 * // You may obtain a copy of the License at
12 * // http://www.apache.org/licenses/LICENSE-2.0
14 * // Unless required by applicable law or agreed to in writing, software
15 * // distributed under the License is distributed on an "AS IS" BASIS,
16 * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * // See the License for the specific language governing permissions and
18 * // limitations under the License.
20 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 #include "JniOnDeviceInfoListener.h"
23 #include "JniOcRepresentation.h"
25 JniOnDeviceInfoListener::JniOnDeviceInfoListener(JNIEnv *env, jobject jListener,
26 RemoveListenerCallback removeListenerCallback)
28 m_jwListener = env->NewWeakGlobalRef(jListener);
29 m_removeListenerCallback = removeListenerCallback;
32 JniOnDeviceInfoListener::~JniOnDeviceInfoListener()
34 LOGI("~JniOnDeviceInfoListener");
38 JNIEnv *env = GetJNIEnv(ret);
44 env->DeleteWeakGlobalRef(m_jwListener);
45 m_jwListener = nullptr;
47 if (JNI_EDETACHED == ret)
49 g_jvm->DetachCurrentThread();
54 void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& ocRepresentation)
57 JNIEnv *env = GetJNIEnv(ret);
63 jobject jListener = env->NewLocalRef(m_jwListener);
66 LOGI("Java onDeviceInfoListener object is already destroyed, quiting");
67 checkExAndRemoveListener(env);
68 if (JNI_EDETACHED == ret)
70 g_jvm->DetachCurrentThread();
75 OCRepresentation* rep = new OCRepresentation(ocRepresentation);
76 jlong handle = reinterpret_cast<jlong>(rep);
77 jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,
82 checkExAndRemoveListener(env);
83 if (JNI_EDETACHED == ret)
85 g_jvm->DetachCurrentThread();
90 jclass clsL = env->GetObjectClass(jListener);
94 checkExAndRemoveListener(env);
95 if (JNI_EDETACHED == ret)
97 g_jvm->DetachCurrentThread();
101 jmethodID midL = env->GetMethodID(clsL, "onDeviceFound", "(Lorg/iotivity/base/OcRepresentation;)V");
105 checkExAndRemoveListener(env);
106 if (JNI_EDETACHED == ret)
108 g_jvm->DetachCurrentThread();
113 env->CallVoidMethod(jListener, midL, jRepresentation);
114 if (env->ExceptionCheck())
116 LOGE("Java exception is thrown");
118 checkExAndRemoveListener(env);
121 if (JNI_EDETACHED == ret)
123 g_jvm->DetachCurrentThread();
127 void JniOnDeviceInfoListener::checkExAndRemoveListener(JNIEnv* env)
129 if (env->ExceptionCheck())
131 jthrowable ex = env->ExceptionOccurred();
132 env->ExceptionClear();
133 m_removeListenerCallback(env, m_jwListener);
134 env->Throw((jthrowable)ex);
138 m_removeListenerCallback(env, m_jwListener);