Add support for Visual Studio 2015 and 2013 builds.
Change-Id: I3ce9bee6b3e57ccd548b849b5d147ca0babd872e
Signed-off-by: David Antler <david.a.antler@intel.com>
JniEntityHandler.cpp \\r
JniOnResourceFoundListener.cpp \\r
JniOnDeviceInfoListener.cpp \\r
- JniOnPlatformInfoListener.cpp \\r
+ JniOnPlatformInfoListener.cpp \\r
JniOnPresenceListener.cpp \\r
JniOnGetListener.cpp \\r
JniOnPutListener.cpp \\r
JniOcPlatform.cpp \\r
JniOcResource.cpp \\r
JniOcResourceIdentifier.cpp \\r
- JniOcSecurity.cpp\r
+ JniOcSecurity.cpp \\r
+ JniOnDPDevicesFoundListener.cpp \\r
+ JniOnDirectPairingListener.cpp \\r
+ JniOcDirectPairDevice.cpp\r
ifeq ($(SECURED), 1)\r
-LOCAL_SRC_FILES += JniOcSecureResource.cpp \\r
- JniOcProvisioning.cpp \\r
- JniSecureUtils.cpp \\r
- JniProvisionResultListner.cpp \\r
- JniPinCheckListener.cpp \\r
- JniDisplayPinListener.cpp\r
-endif\r
+ LOCAL_SRC_FILES += JniOcSecureResource.cpp \\r
+ JniOcProvisioning.cpp \\r
+ JniSecureUtils.cpp \\r
+ JniProvisionResultListner.cpp \\r
+ JniPinCheckListener.cpp \\r
+ JniDisplayPinListener.cpp\r
+ endif\r
\r
LOCAL_LDLIBS := -llog\r
LOCAL_STATIC_LIBRARIES := android-oc\r
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
LOGI("~JniDisplayPinListener()");
if (m_jgListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
if (NULL == env) return;
env->DeleteGlobalRef(m_jgListener);
void JniDisplayPinListener::displayPinCallback(char *pinBuf, size_t pinSize)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (NULL == env)
+ {
+ return;
+ }
jclass clsL = env->GetObjectClass(m_jgListener);
LOGD("~JniEntityHandler");
if (m_jListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
if (nullptr == env)
{
const std::shared_ptr<OCResourceRequest> request)
{
LOGD("JniEntityHandler_handleEntity");
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
if (nullptr == env)
{
jmethodID getValue_ID = env->GetMethodID(clsResult, "getValue", "()I");
if (!getValue_ID)
{
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return OC_EH_ERROR;
}
jint jResult = env->CallIntMethod(entityHandlerResult, getValue_ID);
break;
}
}
+
if (!onEventListener)
{
onEventListener = new T(env, jListener, owner);
{
LOGD("OnEventListener: Failed to create global listener ref.");
delete onEventListener;
+ return nullptr;
}
LOGD("OnEventListener: new listener");
}
+
m_mapMutex.unlock();
return onEventListener;
}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // Copyright 2016 Samsung Electronics All Rights Reserved.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* // http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+
+#include "JniOcDirectPairDevice.h"
+#include "OCDirectPairing.h"
+#include "OCDirectPairing.h"
+using namespace OC;
+namespace PH = std::placeholders;
+
+JniOcDirectPairDevice::JniOcDirectPairDevice(std::shared_ptr<OC::OCDirectPairing> directPairingDevice)
+ : m_sharedDirectPairDevice(directPairingDevice)
+{
+}
+
+JniOcDirectPairDevice::~JniOcDirectPairDevice()
+{
+ LOGD("~JniOcDirectPairDevice()");
+ m_sharedDirectPairDevice = nullptr;
+}
+
+std::string JniOcDirectPairDevice::getHost()
+{
+ return m_sharedDirectPairDevice->getHost();
+}
+
+std::vector<OCPrm_t> JniOcDirectPairDevice::getPairingMethods()
+{
+
+ return m_sharedDirectPairDevice->getPairingMethods();
+}
+
+OCConnectivityType JniOcDirectPairDevice::connectivityType()
+{
+ return m_sharedDirectPairDevice->getConnType();
+}
+
+JniOcDirectPairDevice* JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(JNIEnv *env, jobject thiz)
+{
+ JniOcDirectPairDevice *dpDev = GetHandle<JniOcDirectPairDevice>(env, thiz);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Failed to get native handle from OcDirectPairingDevice");
+ }
+ if (!dpDev)
+ {
+ ThrowOcException(JNI_NO_NATIVE_POINTER, "");
+ }
+ return dpDev;
+}
+std::shared_ptr<OC::OCDirectPairing> JniOcDirectPairDevice::getPtr()
+{
+ return m_sharedDirectPairDevice;
+}
+
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcDirectPairDevice_getHost
+(JNIEnv *env, jobject thiz)
+{
+
+ LOGD("OcDirectPairing_getHost");
+
+ JniOcDirectPairDevice* device = JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(env,thiz);
+ if (!device)
+ {
+ return nullptr;
+ }
+
+ std::string dev = device->getHost();
+ return env->NewStringUTF(dev.c_str());
+}
+
+JNIEXPORT jintArray JNICALL Java_org_iotivity_base_OcDirectPairDevice_getPairingMethods
+ (JNIEnv *env, jobject thiz)
+{
+
+ LOGD("OcDirectPairing_getPairingMethods");
+
+ std::vector<jint> pairingMethodList;
+ JniOcDirectPairDevice* device = JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(env,thiz);
+ if (!device)
+ {
+ return nullptr;
+ }
+
+ std::vector<OCPrm_t> pairingMethods = device->getPairingMethods();
+ return JniOcDirectPairDevice::JconvertIntVectorToJavaList(env,pairingMethods);
+}
+
+
+jintArray JniOcDirectPairDevice::JconvertIntVectorToJavaList(JNIEnv *env, std::vector<OCPrm_t> &vector)
+{
+
+ jsize len = static_cast<jsize>(vector.size());
+
+ jintArray intArray = env->NewIntArray(len);
+ if (!intArray)
+ {
+ return nullptr;
+ }
+
+ env->SetIntArrayRegion(intArray, (jsize)0, len, (const jint*)&vector[0]);
+
+ if (env->ExceptionCheck())
+ {
+ LOGE("ArrayIndexOutOfBoundsException in JconvertIntVectorToJavaList");
+ }
+ return intArray;
+}
+
+/*
+* Class: org_iotivity_base_OcDirectPairDevice
+* Method: getConnectivityTypeN
+* Signature: ()I
+*/
+JNIEXPORT jint JNICALL Java_org_iotivity_base_OcDirectPairDevice_getConnectivityTypeN
+(JNIEnv *env, jobject thiz)
+{
+ LOGD("OcDirectPairDevice_getConnectivityType");
+ JniOcDirectPairDevice* device = JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(env,thiz);
+ if (!device)
+ {
+ return -1;
+ }
+
+ OCConnectivityType connectivityType = device->connectivityType();
+ return static_cast<jint>(connectivityType);
+}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // Copyright 2016 Samsung Electronics All Rights Reserved.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* // http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+
+#include "JniOcStack.h"
+#include "JniOnDPDevicesFoundListener.h"
+#include "OCDirectPairing.h"
+#include <mutex>
+
+#ifndef _Included_org_iotivity_base_OcDirectPairDevice
+#define _Included_org_iotivity_base_OcDirectPairDevice
+
+using namespace OC;
+
+class JniOcDirectPairDevice
+{
+ public:
+ JniOcDirectPairDevice(std::shared_ptr<OCDirectPairing> directPairingDevice);
+ ~JniOcDirectPairDevice();
+
+ static JniOcDirectPairDevice* getJniOcDirectPairDevicePtr(JNIEnv *env, jobject thiz);
+ static jintArray JconvertIntVectorToJavaList(JNIEnv *env, std::vector<OCPrm_t> &vector);
+
+ std::shared_ptr<OCDirectPairing> getPtr();
+ std::string getHost();
+ std::vector<OCPrm_t> getPairingMethods();
+ OCConnectivityType connectivityType();
+
+ private:
+ std::shared_ptr<OCDirectPairing> m_sharedDirectPairDevice;
+};
+
+/* DO NOT EDIT THIS FILE BEYOND THIS LINE - it is machine generated */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ /*
+ * Class: org_iotivity_base_OcDirectPairDevice
+ * Method: getDirectPairedDevices
+ * Signature: (Lorg/iotivity/base/OcDirectPairDevice/GetDirectPairedListener;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcDirectPairDevice_getDirectPairedDevices
+ (JNIEnv *, jobject, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcDirectPairDevice
+ * Method: getHost
+ * Signature: ()Ljava/lang/String;
+ */
+ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcDirectPairDevice_getHost
+ (JNIEnv *, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcDirectPairDevice
+ * Method: getPairingMethods
+ * Signature: ()Ljava/util/List;
+ */
+ JNIEXPORT jintArray JNICALL Java_org_iotivity_base_OcDirectPairDevice_getPairingMethods
+ (JNIEnv *, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcDirectPairDevice
+ * Method: doDirectPairing
+ * Signature: (Lorg/iotivity/base/OcDirectPairDevice;Lorg/iotivity/base/OcPrmType;
+ * Ljava/lang/String;Lorg/iotivity/base/OcDirectPairDevice/DirectPairingListener;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcDirectPairDevice_doDirectPairing
+ (JNIEnv *, jobject, jobject, jint, jstring, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcDirectPairDevice
+ * Method: getConnectivityTypeN
+ * Signature: ()I
+ */
+ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcDirectPairDevice_getConnectivityTypeN
+ (JNIEnv *env, jobject thiz);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+
#include "JniOcPresenceHandle.h"
#include "JniOcResourceResponse.h"
#include "JniOcSecurity.h"
+#include "JniOcDirectPairDevice.h"
#include "JniUtils.h"
#include "ocpayload.h"
presenceMapLock.unlock();
}
+JniOnDPDevicesFoundListener* AddOnDPDevicesFoundListener(JNIEnv* env, jobject jListener)
+{
+ JniOnDPDevicesFoundListener *onDPDeviceListener = nullptr;
+
+ dpDevicesFoundListenerMapLock.lock();
+
+ for (auto it = onDPDevicesFoundListenerMap.begin(); it !=
+ onDPDevicesFoundListenerMap.end(); ++it)
+ {
+ if (env->IsSameObject(jListener, it->first))
+ {
+ auto refPair = it->second;
+ onDPDeviceListener = refPair.first;
+ refPair.second++;
+ it->second = refPair;
+ onDPDevicesFoundListenerMap.insert(*it);
+ LOGD("onDPDeviceListener: ref. count incremented");
+ break;
+ }
+ }
+ if (!onDPDeviceListener)
+ {
+ onDPDeviceListener = new JniOnDPDevicesFoundListener(env, jListener,
+ RemoveOnDPDevicesFoundListener);
+ jobject jgListener = env->NewGlobalRef(jListener);
+ onDPDevicesFoundListenerMap.insert(
+ std::pair<jobject, std::pair<JniOnDPDevicesFoundListener*, int>>(
+ jgListener,
+ std::pair<JniOnDPDevicesFoundListener*, int>(onDPDeviceListener, 1)));
+ LOGI("onDPDeviceListener: new listener");
+ }
+ dpDevicesFoundListenerMapLock.unlock();
+ return onDPDeviceListener;
+}
+
+void RemoveOnDPDevicesFoundListener(JNIEnv* env, jobject jListener)
+{
+ dpDevicesFoundListenerMapLock.lock();
+ bool isFound = false;
+ for (auto it = onDPDevicesFoundListenerMap.begin(); it !=
+ onDPDevicesFoundListenerMap.end(); ++it)
+ {
+ if (env->IsSameObject(jListener, it->first))
+ {
+ auto refPair = it->second;
+ if (refPair.second > 1)
+ {
+ refPair.second--;
+ it->second = refPair;
+ onDPDevicesFoundListenerMap.insert(*it);
+ LOGI("onDPDeviceListener: ref. count decremented");
+ }
+ else
+ {
+ env->DeleteGlobalRef(it->first);
+ JniOnDPDevicesFoundListener* listener = refPair.first;
+ delete listener;
+ onDPDevicesFoundListenerMap.erase(it);
+ LOGI("onDPDeviceListener is removed");
+ }
+ isFound = true;
+ break;
+ }
+ }
+ if (!isFound)
+ {
+ ThrowOcException(JNI_EXCEPTION, "onDPDeviceListener not found");
+ }
+ dpDevicesFoundListenerMapLock.unlock();
+}
+
+JniOnDirectPairingListener* AddOnDirectPairingListener(JNIEnv* env, jobject jListener)
+{
+ JniOnDirectPairingListener *onDirectPairingListener = nullptr;
+
+ directPairingListenerMapLock.lock();
+
+ for (auto it = directPairingListenerMap.begin(); it !=
+ directPairingListenerMap.end(); ++it)
+ {
+ if (env->IsSameObject(jListener, it->first))
+ {
+ auto refPair = it->second;
+ onDirectPairingListener = refPair.first;
+ refPair.second++;
+ it->second = refPair;
+ directPairingListenerMap.insert(*it);
+ LOGD("onDirectPairingListener: ref. count incremented");
+ break;
+ }
+ }
+ if (!onDirectPairingListener)
+ {
+ onDirectPairingListener = new JniOnDirectPairingListener(env, jListener,
+ RemoveOnDirectPairingListener);
+ jobject jgListener = env->NewGlobalRef(jListener);
+ directPairingListenerMap.insert(
+ std::pair<jobject, std::pair<JniOnDirectPairingListener*, int>>(
+ jgListener,
+ std::pair<JniOnDirectPairingListener*, int>(onDirectPairingListener, 1)));
+ LOGI("onDirectPairingListener: new listener");
+ }
+ directPairingListenerMapLock.unlock();
+ return onDirectPairingListener;
+}
+
+void RemoveOnDirectPairingListener(JNIEnv* env, jobject jListener)
+{
+ directPairingListenerMapLock.lock();
+ bool isFound = false;
+ for (auto it = directPairingListenerMap.begin(); it !=
+ directPairingListenerMap.end(); ++it)
+ {
+ if (env->IsSameObject(jListener, it->first))
+ {
+ auto refPair = it->second;
+ if (refPair.second > 1)
+ {
+ refPair.second--;
+ it->second = refPair;
+ directPairingListenerMap.insert(*it);
+ LOGI("onDirectPairingListener: ref. count decremented");
+ }
+ else
+ {
+ env->DeleteGlobalRef(it->first);
+ JniOnDirectPairingListener* listener = refPair.first;
+ delete listener;
+ directPairingListenerMap.erase(it);
+ LOGI("onDirectPairingListener is removed");
+ }
+ isFound = true;
+ break;
+ }
+ }
+ if (!isFound)
+ {
+ ThrowOcException(JNI_EXCEPTION, "onDirectPairingListener not found");
+ }
+ directPairingListenerMapLock.unlock();
+}
+
/*
* Class: org_iotivity_base_OcPlatform
* Method: configure
JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(
env, jResourceHandle);
- if (!jniOcResourceHandle) return;
+ if (!jniOcResourceHandle)
+ {
+ return;
+ }
try
{
return;
}
- try{
+ try {
OCStackResult result = OCPlatform::notifyAllObservers(
jniOcResourceHandle->getOCResourceHandle(),
JniUtils::getQOS(env, static_cast<int>(jQoS)));
}
/*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: findDirectPairingDevices
+ * Signature: (ILorg/iotivity/base/OcPlatform/FindDirectPairingListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findDirectPairingDevices
+ (JNIEnv * env, jclass clazz, jint jTimeout, jobject jListener)
+{
+ LOGD("OcPlatform_findDirectPairingDevices");
+
+ if (!jListener)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "onDPDevicesFoundListener cannot be null");
+ return;
+ }
+ JniOnDPDevicesFoundListener *onDPDevsFoundListener = AddOnDPDevicesFoundListener(env,
+ jListener);
+
+ GetDirectPairedCallback getDirectPairedCallback =
+ [onDPDevsFoundListener](PairedDevices pairingDevList)
+ {
+ onDPDevsFoundListener->directPairingDevicesCallback(pairingDevList,
+ DPFunc::FIND_DIRECT_PAIRED_DEV_LIST);
+ };
+
+ try
+ {
+ OCStackResult result = OCPlatform::findDirectPairingDevices(jTimeout,
+ getDirectPairedCallback);
+ if (OC_STACK_OK != result)
+ {
+ ThrowOcException(result, "OCPlatform::findDirectPairingDevices has failed");
+ return;
+ }
+ }
+ catch (OCException& e)
+ {
+ LOGE("%s", e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
+ }
+}
+
+/*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: getDirectPairedDevices
+ * Signature: (Lorg/iotivity/base/OcDirectPairDevice/GetDirectPairedListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDirectPairedDevices
+(JNIEnv *env, jclass jclazz, jobject jListener)
+{
+ LOGD("OcPlatform_getDirectPairedDevices");
+
+ if (!jListener)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "getPairedDevList Callback cannot be null");
+ return;
+ }
+ JniOnDPDevicesFoundListener *onGetPairedDevicesListener = AddOnDPDevicesFoundListener(env,
+ jListener);
+
+ GetDirectPairedCallback getDirectPairedCallback =
+ [onGetPairedDevicesListener](PairedDevices pairedDevList)
+ {
+ onGetPairedDevicesListener->directPairingDevicesCallback(pairedDevList,
+ DPFunc::GET_PAIRED_DEV_LIST);
+ };
+
+ try
+ {
+ OCStackResult result = OCPlatform::getDirectPairedDevices(getDirectPairedCallback);
+ if (OC_STACK_OK != result)
+ {
+ ThrowOcException(result, "OcDirectPairDevice_getDirectPairedDevices");
+ return;
+ }
+ }
+ catch (OCException& e)
+ {
+ LOGE("%s", e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
+ }
+}
+
+/*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: doDirectPairing
+ * Signature: (Lorg/iotivity/base/OcDirectPairDevice;Lorg/iotivity/base/OcPrmType;
+ * Ljava/lang/String;Lorg/iotivity/base/OcDirectPairDevice/DirectPairingListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_doDirectPairing0
+(JNIEnv *env, jclass clazz, jobject jpeer, jint jprmType, jstring jpin, jobject jListener)
+{
+ LOGD("OcPlatform_doDirectPairing");
+
+ if (!jListener)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "doDirectPairing Callback cannot be null");
+ return;
+ }
+ if (!jpeer)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Peer cannot be null");
+ return;
+ }
+
+ JniOnDirectPairingListener *onDirectPairingListener = AddOnDirectPairingListener(env,
+ jListener);
+
+ DirectPairingCallback DirectPairingCB =
+ [onDirectPairingListener](std::shared_ptr<OCDirectPairing> dpDev, OCStackResult result)
+ {
+ onDirectPairingListener->doDirectPairingCB(dpDev, result);
+ };
+
+ JniOcDirectPairDevice *dev = JniOcDirectPairDevice::getJniOcDirectPairDevicePtr(env, jpeer);
+
+ if (!dev)
+ {
+ return ;
+ }
+ std::string pin = env->GetStringUTFChars(jpin, 0);
+
+ try
+ {
+ OCStackResult result = OCPlatform::doDirectPairing(dev->getPtr(), (OCPrm_t)jprmType,
+ pin, DirectPairingCB);
+ if (OC_STACK_OK != result)
+ {
+ ThrowOcException(result, "OcPlatform_oDirectPairing");
+ return;
+ }
+ }
+ catch (OCException& e)
+ {
+ LOGE("%s", e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
+ }
+}
+
+/*
* Class: org_iotivity_base_OcPlatform
* Method: getDeviceInfo0
* Signature: (Ljava/lang/String;Ljava/lang/String;ILorg/iotivity/base/OcPlatform/OnDeviceFoundListener;)V
return nullptr;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, jResource);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
OCResourceHandle resourceHandle;
try
jstring jStr = (jstring)env->GetObjectArrayElement(jDeviceTypes, i);
if (!jStr)
{
+ delete deviceInfo.deviceName;
ThrowOcException(OC_STACK_INVALID_PARAM, "device type cannot be null");
return;
}
OCResourcePayloadAddStringLL(&deviceInfo.types, env->GetStringUTFChars(jStr, nullptr));
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ delete deviceInfo.deviceName;
+ return;
+ }
env->DeleteLocalRef(jStr);
}
}
JniOcResourceHandle* jniOcResourceCollectionHandle =
JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceCollectionHandle);
- if (!jniOcResourceCollectionHandle) return;
+ if (!jniOcResourceCollectionHandle)
+ {
+ return;
+ }
JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(
env, jResourceHandle);
JniOcResourceHandle* jniOcResourceHandle =
JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
- if (!jniOcResourceHandle) return;
+ if (!jniOcResourceHandle)
+ {
+ return;
+ }
try
{
JniOcResourceResponse *jniResponse =
JniOcResourceResponse::getJniOcResourceResponsePtr(env, jResourceResponse);
- if (!jniResponse) return;
+ if (!jniResponse)
+ {
+ return;
+ }
try
{
#include "JniOnResourceFoundListener.h"
#include "JniOnDeviceInfoListener.h"
#include "JniOnPlatformInfoListener.h"
+#include "JniOnDPDevicesFoundListener.h"
+#include "JniOnDirectPairingListener.h"
#include "JniOnPresenceListener.h"
#include <mutex>
JniOnPresenceListener* AddOnPresenceListener(JNIEnv* env, jobject jListener);
void RemoveOnPresenceListener(JNIEnv* env, jobject jListener);
+JniOnDPDevicesFoundListener* AddOnDPDevicesFoundListener(JNIEnv* env, jobject jListener);
+void RemoveOnDPDevicesFoundListener(JNIEnv* env, jobject jListener);
+
+JniOnDirectPairingListener* AddOnDirectPairingListener(JNIEnv* env, jobject jListener);
+void RemoveOnDirectPairingListener(JNIEnv* env, jobject jListener);
+
+
std::map<jobject, std::pair<JniOnResourceFoundListener*, int>> onResourceFoundListenerMap;
std::map<jobject, std::pair<JniOnDeviceInfoListener*, int>> onDeviceInfoListenerMap;
std::map<jobject, std::pair<JniOnPlatformInfoListener*, int>> onPlatformInfoListenerMap;
std::map<jobject, std::pair<JniOnPresenceListener*, int>> onPresenceListenerMap;
+std::map<jobject, std::pair<JniOnDPDevicesFoundListener*, int>> onDPDevicesFoundListenerMap;
+std::map<jobject, std::pair<JniOnDirectPairingListener*, int>> directPairingListenerMap;
std::mutex resourceFoundMapLock;
std::mutex deviceInfoMapLock;
std::mutex platformInfoMapLock;
std::mutex presenceMapLock;
+std::mutex dpDevicesFoundListenerMapLock;
+std::mutex directPairingListenerMapLock;
#ifdef __cplusplus
extern "C" {
JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_sendResponse0
(JNIEnv *, jclass, jobject);
+ /*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: findDirectPairingDevices
+ * Signature: (ILorg/iotivity/base/OcPlatform/FindDirectPairingListener;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findDirectPairingDevices
+ (JNIEnv *, jclass, jint, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: getDirectPairedDevices
+ * Signature: (Lorg/iotivity/base/OcDirectPairDevice/GetDirectPairedListener;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDirectPairedDevices
+ (JNIEnv *, jclass, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcPlatform
+ * Method: doDirectPairing
+ * Signature: (Lorg/iotivity/base/OcDirectPairDevice;Lorg/iotivity/base/OcPrmType;
+ * Ljava/lang/String;Lorg/iotivity/base/OcDirectPairDevice/DirectPairingListener;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_doDirectPairing0
+ (JNIEnv *, jclass, jobject, jint, jstring, jobject);
#ifdef __cplusplus
}
#endif
JniOcPresenceHandle::JniOcPresenceHandle(JniOnPresenceListener* jniListener, OCPresenceHandle presenceHandle)
: m_jniListener(jniListener), m_presenceHandle(presenceHandle)
-{}
+{
+}
JniOcPresenceHandle::~JniOcPresenceHandle()
{
LOGD("OcPresenceHandle_dispose");
JniOcPresenceHandle *presenceHandle = JniOcPresenceHandle::getJniOcPresenceHandlePtr(env, thiz);
delete presenceHandle;
-}
\ No newline at end of file
+}
{
LOGD("OcRepresentation_getValues");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::map<std::string, AttributeValue> values = rep->getValues();
jobject jHashMap = env->NewObject(g_cls_HashMap, g_mid_HashMap_ctor);
- if (!jHashMap) return nullptr;
+ if (!jHashMap)
+ {
+ return nullptr;
+ }
- for (std::map<std::string, AttributeValue>::const_iterator it = values.begin(); it != values.end(); it++) {
+ for (std::map<std::string, AttributeValue>::const_iterator it = values.begin(); it != values.end(); it++)
+ {
jobject key = static_cast<jobject>(env->NewStringUTF(it->first.c_str()));
jobject val = boost::apply_visitor(JObjectConverter(env), it->second);
env->CallObjectMethod(jHashMap, g_mid_HashMap_put, key, val);
return nullptr;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string str = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(str, static_cast<int>(jValue));
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string str = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(str, static_cast<double>(jValue));
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string str = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(str, static_cast<bool>(jValue));
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
std::string value = env->GetStringUTFChars(jValue, nullptr);
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
if (jValue)
{
OCRepresentation *value = JniOcRepresentation::getOCRepresentationPtr(env, jValue);
- if (!value) return;
+ if (!value)
+ {
+ return;
+ }
rep->setValue(key, *value);
}
else
env->ReleaseIntArrayElements(jValue, ints, JNI_ABORT);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
env->ReleaseDoubleArrayElements(jValue, doubles, JNI_ABORT);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
env->ReleaseBooleanArrayElements(jValue, booleans, JNI_ABORT);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
JniUtils::convertJavaStrArrToStrVector(env, jValue, value);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
-
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
JniUtils::convertJavaRepresentationArrToVector(env, jValue, value);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
env->ReleaseByteArrayElements(jValue, bytes, JNI_ABORT);
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string key = env->GetStringUTFChars(jKey, nullptr);
rep->setValue(key, value);
{
LOGD("OcRepresentation_addChild");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
OCRepresentation *child = JniOcRepresentation::getOCRepresentationPtr(env, jOcRepresentation);
- if (!child) return;
+ if (!child)
+ {
+ return;
+ }
rep->addChild(*child);
}
{
LOGD("OcRepresentation_clearChildren");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
rep->clearChildren();
}
{
LOGD("OcRepresentation_getChildrenArray");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
return JniUtils::convertRepresentationVectorToJavaArray(env, rep->getChildren());
}
{
LOGD("OcRepresentation_getUri");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::string uri(rep->getUri());
return env->NewStringUTF(uri.c_str());
{
LOGD("OcRepresentation_getHost");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::string uri(rep->getHost());
return env->NewStringUTF(uri.c_str());
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
rep->setUri(env->GetStringUTFChars(jUri, nullptr));
}
return false;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return false;
+ if (!rep)
+ {
+ return false;
+ }
std::string str = env->GetStringUTFChars(jstr, nullptr);
return rep->hasAttribute(str);
{
LOGD("OcRepresentation_getResourceTypes");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::vector<std::string> resourceTypes = rep->getResourceTypes();
return JniUtils::convertStrVectorToJavaStrList(env, resourceTypes);
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::vector<std::string> resourceTypes;
JniUtils::convertJavaStrArrToStrVector(env, jResourceTypeArray, resourceTypes);
{
LOGD("OcRepresentation_getResourceInterfaces");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return nullptr;
+ if (!rep)
+ {
+ return nullptr;
+ }
std::vector<std::string> resourceInterfaces = rep->getResourceInterfaces();
return JniUtils::convertStrVectorToJavaStrList(env, resourceInterfaces);
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::vector<std::string> resourceInterfaces;
JniUtils::convertJavaStrArrToStrVector(env, jResourceInterfaceArray, resourceInterfaces);
{
LOGD("OcRepresentation_isEmpty");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return false;
+ if (!rep)
+ {
+ return false;
+ }
return static_cast<jboolean>(rep->empty());
}
{
LOGD("OcRepresentation_size");
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return -1;
+ if (!rep)
+ {
+ return -1;
+ }
return static_cast<jint>(rep->numberOfAttributes());
}
return false;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return false;
+ if (!rep)
+ {
+ return false;
+ }
std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
return static_cast<jboolean>(rep->erase(attributeKey));
return;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return;
+ if (!rep)
+ {
+ return;
+ }
std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
rep->setNULL(attributeKey);
return false;
}
OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
- if (!rep) return false;
+ if (!rep)
+ {
+ return false;
+ }
std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
return static_cast<jboolean>(rep->isNULL(attributeKey));
struct JObjectConverter : boost::static_visitor < jobject >
{
- JObjectConverter(JNIEnv *env) : env(env){}
+ JObjectConverter(JNIEnv *env) : env(env)
+ {
+ }
+
+ jobject operator()(const NullType&) const
+ {
+ return nullptr;
+ }
- jobject operator()(const NullType&) const { return nullptr; }
jobject operator()(const int& val) const
{
jobject jobj = env->NewObject(
{
size_t len = val.size();
jintArray jIntArray = env->NewIntArray(len);
- if (!jIntArray) return nullptr;
+ if (!jIntArray)
+ {
+ return nullptr;
+ }
const int* ints = &val[0];
env->SetIntArrayRegion(jIntArray, 0, len, reinterpret_cast<const jint*>(ints));
return jIntArray;
{
size_t len = val.size();
jdoubleArray jDoubleArray = env->NewDoubleArray(len);
- if (!jDoubleArray) return nullptr;
+ if (!jDoubleArray)
+ {
+ return nullptr;
+ }
const double* doubles = &val[0];
env->SetDoubleArrayRegion(jDoubleArray, 0, len, reinterpret_cast<const jdouble*>(doubles));
return jDoubleArray;
{
size_t len = val.size();
jbooleanArray jBooleanArray = env->NewBooleanArray(len);
- if (!jBooleanArray) return nullptr;
+ if (!jBooleanArray)
+ {
+ return nullptr;
+ }
jboolean* booleans = new jboolean[len];
- for (size_t i = 0; i < len; ++i) {
+ for (size_t i = 0; i < len; ++i)
+ {
booleans[i] = static_cast<jboolean>(val[i]);
}
env->SetBooleanArrayRegion(jBooleanArray, 0, len, booleans);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
return jBooleanArray;
}
{
size_t len = val.size();
jobjectArray strArr = env->NewObjectArray(len, g_cls_String, nullptr);
- if (!strArr) return nullptr;
+ if (!strArr)
+ {
+ return nullptr;
+ }
for (size_t i = 0; i < len; ++i)
{
jstring jString = env->NewStringUTF(val[i].c_str());
env->SetObjectArrayElement(strArr, static_cast<jsize>(i), jString);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jString);
}
return strArr;
{
jsize len = static_cast<jsize>(val.size());
jobjectArray repArr = env->NewObjectArray(len, g_cls_OcRepresentation, nullptr);
- if (!repArr) return nullptr;
+ if (!repArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < len; ++i)
{
OCRepresentation* rep = new OCRepresentation(val[i]);
{
size_t len = val.size();
jbyteArray jByteArray = env->NewByteArray(len);
- if (!jByteArray) return nullptr;
+ if (!jByteArray)
+ {
+ return nullptr;
+ }
const uint8_t* bytes = &val[0];
env->SetByteArrayRegion(jByteArray, 0, len, reinterpret_cast<const jbyte*>(bytes));
return jByteArray;
{
size_t lenInner = val[i].size();
jintArray jIntArray = env->NewIntArray(lenInner);
- if (!jIntArray) return nullptr;
+ if (!jIntArray)
+ {
+ return nullptr;
+ }
const int* ints = &val[i][0];
env->SetIntArrayRegion(jIntArray, 0, lenInner, reinterpret_cast<const jint*>(ints));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jOuterArr, i, static_cast<jobject>(jIntArray));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jIntArray);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_int2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
+
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_int1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
+
for (jsize i = 0; i < lenMiddle; ++i)
{
jsize lenInner = static_cast<jsize>(val[k][i].size());
jintArray jIntArray = env->NewIntArray(lenInner);
- if (!jIntArray) return nullptr;
+ if (!jIntArray)
+ {
+ return nullptr;
+ }
const int* ints = &val[k][i][0];
env->SetIntArrayRegion(jIntArray, 0, lenInner, reinterpret_cast<const jint*>(ints));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jMiddleArr, i, jIntArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jIntArray);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_double1DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
+
for (jsize i = 0; i < lenOuter; ++i)
{
size_t lenInner = val[i].size();
jdoubleArray jDoubleArray = env->NewDoubleArray(lenInner);
- if (!jDoubleArray) return nullptr;
+ if (!jDoubleArray)
+ {
+ return nullptr;
+ }
+
const double* doubles = &val[i][0];
env->SetDoubleArrayRegion(jDoubleArray, 0, lenInner, reinterpret_cast<const jdouble*>(doubles));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jOuterArr, i, jDoubleArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jDoubleArray);
}
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_double2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_double1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenMiddle; ++i)
{
jsize lenInner = static_cast<jsize>(val[k][i].size());
jdoubleArray jDoubleArray = env->NewDoubleArray(lenInner);
- if (!jDoubleArray) return nullptr;
+ if (!jDoubleArray)
+ {
+ return nullptr;
+ }
const double* doubles = &val[k][i][0];
env->SetDoubleArrayRegion(jDoubleArray, 0, lenInner, reinterpret_cast<const jdouble*>(doubles));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jMiddleArr, i, jDoubleArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jDoubleArray);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_boolean1DArray, 0);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenOuter; ++i)
{
size_t lenInner = val[i].size();
jbooleanArray jBooleanArray = env->NewBooleanArray(lenInner);
- if (!jBooleanArray) return nullptr;
+ if (!jBooleanArray)
+ {
+ return nullptr;
+ }
jboolean* booleans = new jboolean[lenInner];
- for (size_t j = 0; j < lenInner; ++j) {
+ for (size_t j = 0; j < lenInner; ++j)
+ {
booleans[j] = static_cast<jboolean>(val[i][j]);
}
env->SetBooleanArrayRegion(jBooleanArray, 0, lenInner, booleans);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jOuterArr, i, jBooleanArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jBooleanArray);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_boolean2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_boolean1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenMiddle; ++i)
{
size_t lenInner = val[k][i].size();
jbooleanArray jBooleanArray = env->NewBooleanArray(lenInner);
jboolean* booleans = new jboolean[lenInner];
- for (size_t j = 0; j < lenInner; ++j) {
+ for (size_t j = 0; j < lenInner; ++j)
+ {
booleans[j] = val[k][i][j];
}
env->SetBooleanArrayRegion(jBooleanArray, 0, lenInner, booleans);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->SetObjectArrayElement(jMiddleArr, i, jBooleanArray);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->ReleaseBooleanArrayElements(jBooleanArray, booleans, 0);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jBooleanArray);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
- env->DeleteLocalRef(jMiddleArr);
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ } env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
}
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_String1DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenOuter; ++i)
{
jsize lenInner = static_cast<jsize>(val[i].size());
jobjectArray strArr = env->NewObjectArray(lenInner, g_cls_String, nullptr);
- if (!strArr) return nullptr;
+ if (!strArr)
+ {
+ return nullptr;
+ }
for (jsize j = 0; j < lenInner; ++j)
{
jstring jString = env->NewStringUTF(val[i][j].c_str());
env->SetObjectArrayElement(strArr, j, jString);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jString);
}
env->SetObjectArrayElement(jOuterArr, i, strArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(strArr);
}
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_String2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_String1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenMiddle; ++i)
{
jsize lenInner = static_cast<jsize>(val[k][i].size());
jobjectArray strArr = env->NewObjectArray(lenInner, g_cls_String, nullptr);
- if (!strArr) return nullptr;
+ if (!strArr)
+ {
+ return nullptr;
+ }
for (jsize j = 0; j < lenInner; ++j)
{
jstring jString = env->NewStringUTF(val[k][i][j].c_str());
env->SetObjectArrayElement(strArr, j, jString);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jString);
}
env->SetObjectArrayElement(jMiddleArr, i, strArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(strArr);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_OcRepresentation1DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenOuter; ++i)
{
jsize lenInner = static_cast<jsize>(val[i].size());
jobjectArray repArr = env->NewObjectArray(lenInner, g_cls_OcRepresentation, nullptr);
- if (!repArr) return nullptr;
+ if (!repArr)
+ {
+ return nullptr;
+ }
for (jsize j = 0; j < lenInner; ++j)
{
OCRepresentation* rep = new OCRepresentation(val[i][j]);
return nullptr;
}
env->SetObjectArrayElement(repArr, j, jRepresentation);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jRepresentation);
}
env->SetObjectArrayElement(jOuterArr, i, repArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(repArr);
}
return jOuterArr;
{
jsize lenOuter = static_cast<jsize>(val.size());
jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_OcRepresentation2DArray, nullptr);
- if (!jOuterArr) return nullptr;
+ if (!jOuterArr)
+ {
+ return nullptr;
+ }
for (jsize k = 0; k < lenOuter; ++k)
{
jsize lenMiddle = static_cast<jsize>(val[k].size());
jobjectArray jMiddleArr = env->NewObjectArray(lenMiddle, g_cls_OcRepresentation1DArray, nullptr);
- if (!jMiddleArr) return nullptr;
+ if (!jMiddleArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < lenMiddle; ++i)
{
jsize lenInner = static_cast<jsize>(val[k][i].size());
jobjectArray repArr = env->NewObjectArray(lenInner, g_cls_OcRepresentation, nullptr);
- if (!repArr) return nullptr;
+ if (!repArr)
+ {
+ return nullptr;
+ }
for (jsize j = 0; j < lenInner; ++j)
{
OCRepresentation* rep = new OCRepresentation(val[k][i][j]);
return nullptr;
}
env->SetObjectArrayElement(repArr, j, jRepresentation);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jRepresentation);
}
env->SetObjectArrayElement(jMiddleArr, i, repArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(repArr);
}
env->SetObjectArrayElement(jOuterArr, k, jMiddleArr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jMiddleArr);
}
return jOuterArr;
#include "JniOcRequestHandle.h"
JniOcRequestHandle::JniOcRequestHandle(OCRequestHandle requestHandle) : m_requestHandle(requestHandle)
-{}
+{
+}
JniOcRequestHandle::~JniOcRequestHandle()
{
LOGD("OcRequestHandle_dispose");
JniOcRequestHandle *handle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, thiz);
delete handle;
-}
\ No newline at end of file
+}
JniOcResource::JniOcResource(std::shared_ptr<OCResource> resource)
: m_sharedResource(resource)
-{}
+{
+}
JniOcResource::~JniOcResource()
{
m_sharedResource = nullptr;
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
m_onGetManager.removeAllListeners(env);
m_onPutManager.removeAllListeners(env);
m_onDeleteManager.removeAllListeners(env);
m_onObserveManager.removeAllListeners(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
OCStackResult JniOcResource::get(JNIEnv* env, const QueryParamsMap &queryParametersMap, jobject jListener)
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
resourceInterface = env->GetStringUTFChars(jResourceInterface, nullptr);
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env, jRepresentation);
- if (!representation) return;
+ if (!representation)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
try
{
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
try
{
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
QueryParamsMap qpm;
JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
{
LOGD("OcResource_cancelObserve1");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
try
{
return;
}
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
HeaderOptions headerOptions;
JniUtils::convertJavaHeaderOptionsArrToVector(env, jheaderOptionArr, headerOptions);
{
LOGD("OcResource_unsetHeaderOptions");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return;
+ if (!resource)
+ {
+ return;
+ }
resource->unsetHeaderOptions();
}
{
LOGD("OcResource_getHost");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
return env->NewStringUTF(resource->host().c_str());
}
{
LOGD("OcResource_getUri");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
return env->NewStringUTF(resource->uri().c_str());
}
{
LOGD("OcResource_getConnectivityType");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return -1;
+ if (!resource)
+ {
+ return -1;
+ }
OCConnectivityType connectivityType = resource->connectivityType();
return static_cast<jint>(connectivityType);
{
LOGD("OcResource_isObservable");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
+ if (!resource)
+ {
+ return false;
+ }
+
return (jboolean)resource->isObservable();
}
{
LOGD("OcResource_getResourceTypes");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
std::vector<std::string> resourceTypes = resource->getResourceTypes();
{
LOGD("OcResource_getResourceInterfaces");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
std::vector<std::string> resourceInterfaces = resource->getResourceInterfaces();
{
LOGD("OcResource_getUniqueIdentifier");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
JniOcResourceIdentifier *jniResourceIdentifier =
new JniOcResourceIdentifier(resource->uniqueIdentifier());
- if (!jniResourceIdentifier) return nullptr;
+ if (!jniResourceIdentifier)
+ {
+ return nullptr;
+ }
jlong handle = reinterpret_cast<jlong>(jniResourceIdentifier);
jobject jResourceIdentifier = env->NewObject(g_cls_OcResourceIdentifier,
{
LOGD("OcResource_getServerId");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
- if (!resource) return nullptr;
+ if (!resource)
+ {
+ return nullptr;
+ }
return env->NewStringUTF(resource->sid().c_str());
}
LOGD("OcResource_dispose");
JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
delete resource;
-}
\ No newline at end of file
+}
JniOcResourceHandle::JniOcResourceHandle(OCResourceHandle resourceHandle)
: m_resourceHandle(resourceHandle)
-{}
+{
+}
JniOcResourceHandle::~JniOcResourceHandle()
{
LOGD("OcResourceHandle_dispose");
JniOcResourceHandle *resourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, thiz);
delete resourceHandle;
-}
\ No newline at end of file
+}
JniOcResourceIdentifier::JniOcResourceIdentifier(OC::OCResourceIdentifier resourceIdentifier)
: m_resourceIdentifier(resourceIdentifier)
-{}
+{
+}
JniOcResourceIdentifier::~JniOcResourceIdentifier()
{
(JNIEnv *env, jobject jThiz, jobject jOther)
{
JniOcResourceIdentifier *thiz = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, jThiz);
- if (!thiz) return false;
+ if (!thiz)
+ {
+ return false;
+ }
JniOcResourceIdentifier *other = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, jOther);
- if (!other) return false;
+ if (!other)
+ {
+ return false;
+ }
if (thiz->getOCResourceIdentifier() == other->getOCResourceIdentifier())
{
LOGD("JniOcResourceIdentifier_dispose");
JniOcResourceIdentifier *identifier = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, thiz);
delete identifier;
-}
\ No newline at end of file
+}
JniOcResourceRequest::JniOcResourceRequest(const std::shared_ptr<OCResourceRequest> request)
: m_request(request)
-{}
+{
+}
JniOcResourceRequest::~JniOcResourceRequest()
-{}
+{
+}
std::string
JniOcResourceRequest::getRequestType()
{
LOGD("OcResourceRequest_getRequestTypeNative");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
-
+ if (!request)
+ {
+ return nullptr;
+ }
std::string requestType = request->getRequestType();
return env->NewStringUTF(requestType.c_str());
}
{
LOGD("OcResourceRequest_getQueryParameters");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
+ if (!request)
+ {
+ return nullptr;
+ }
return JniUtils::convertQueryParamsMapToJavaMap(env, request->getQueryParameters());
}
{
LOGD("OcResourceRequest_getRequestHandlerFlagNative");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return -1;
+ if (!request)
+ {
+ return -1;
+ }
return static_cast<jint>(request->getRequestHandlerFlag());
}
{
LOGD("OcResourceRequest_getResourceRepresentation");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
+ if (!request)
+ {
+ return nullptr;
+ }
OCRepresentation *ocRepresentation = new OCRepresentation(request->getResourceRepresentation());
- if (!ocRepresentation) return nullptr;
+ if (!ocRepresentation)
+ {
+ return nullptr;
+ }
jlong handle = reinterpret_cast<jlong>(ocRepresentation);
jobject jRepresentation = env->NewObject(g_cls_OcRepresentation, g_mid_OcRepresentation_N_ctor_bool,
{
LOGD("OcResourceRequest_getObservationInfo");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
-
+ if (!request)
+ {
+ return nullptr;
+ }
ObservationInfo oInfo = request->getObservationInfo();
jobject jObservationInfo = env->NewObject(g_cls_ObservationInfo, g_mid_ObservationInfo_N_ctor,
return;
}
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return;
-
+ if (!request)
+ {
+ return;
+ }
request->setResourceUri(env->GetStringUTFChars(jUri, 0));
}
{
LOGD("OcResourceRequest_getResourceUri");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
-
+ if (!request)
+ {
+ return nullptr;
+ }
std::string requestUri = request->getResourceUri();
return env->NewStringUTF(requestUri.c_str());
}
{
LOGD("OcResourceRequest_getHeaderOptions");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
-
+ if (!request)
+ {
+ return nullptr;
+ }
return JniUtils::convertHeaderOptionsVectorToJavaList(env, request->getHeaderOptions());
}
{
LOGD("OcResourceRequest_getRequestHandle");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
+ if (!request)
+ {
+ return nullptr;
+ }
JniOcRequestHandle* jniHandle = new JniOcRequestHandle(request->getRequestHandle());
jlong handle = reinterpret_cast<jlong>(jniHandle);
{
LOGD("OcResourceRequest_getResourceHandle");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
- if (!request) return nullptr;
+ if (!request)
+ {
+ return nullptr;
+ }
JniOcResourceHandle* jniHandle = new JniOcResourceHandle(
request->getResourceHandle());
LOGD("OcResourceRequest_dispose");
JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
delete request;
-}
\ No newline at end of file
+}
JniOcResourceResponse::JniOcResourceResponse
(std::shared_ptr<OCResourceResponse> resourceResponse)
-: m_response(resourceResponse){}
+: m_response(resourceResponse)
+{
+}
JniOcResourceResponse::~JniOcResourceResponse()
-{}
+{
+}
void JniOcResourceResponse::setErrorCode(const int eCode)
{
{
LOGD("OcResourceResponse_setErrorCode");
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
response->setErrorCode(static_cast<int>(eCode));
}
{
LOGD("OcResourceResponse_getNewResourceUri");
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return nullptr;
-
+ if (!response)
+ {
+ return nullptr;
+ }
return env->NewStringUTF(response->getNewResourceUri().c_str());
}
{
LOGD("OcResourceResponse_setNewResourceUri");
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
response->setNewResourceUri(env->GetStringUTFChars(jstr, 0));
}
return;
}
JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!jniResponse) return;
-
+ if (!jniResponse)
+ {
+ return;
+ }
HeaderOptions headerOptions;
JniUtils::convertJavaHeaderOptionsArrToVector(env, jHeaderOptions, headerOptions);
return;
}
JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!jniResponse) return;
-
+ if (!jniResponse)
+ {
+ return;
+ }
JniOcRequestHandle* jniOcRequestHandle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, jRequestHandle);
- if (!jniOcRequestHandle) return;
-
+ if (!jniOcRequestHandle)
+ {
+ return;
+ }
jniResponse->setRequestHandle(jniOcRequestHandle->getOCRequestHandle());
}
return;
}
JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!jniResponse) return;
-
+ if (!jniResponse)
+ {
+ return;
+ }
JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
- if (!jniOcResourceHandle) return;
-
+ if (!jniOcResourceHandle)
+ {
+ return;
+ }
jniResponse->setResourceHandle(jniOcResourceHandle->getOCResourceHandle());
}
{
LOGD("OcResourceResponse_setResponseResult");
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
response->setResponseResult(JniUtils::getOCEntityHandlerResult(env, static_cast<int>(responseResult)));
}
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env,
thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
jRepresentation);
- if (!representation) return;
-
+ if (!representation)
+ {
+ return;
+ }
response->setResourceRepresentation(*representation, env->GetStringUTFChars(jstr, 0));
}
return;
}
JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response) return;
-
+ if (!response)
+ {
+ return;
+ }
OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
jRepresentation);
LOGD("OcResourceResponse_dispose");
JniOcResourceResponse *resp = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
delete resp;
-}
\ No newline at end of file
+}
#include "JniOcSecureResource.h"
#include "JniSecureUtils.h"
+#include "oic_string.h"
namespace PH = std::placeholders;
JniOcSecureResource::JniOcSecureResource(std::shared_ptr<OCSecureResource> device)
: m_sharedSecureResource(device)
-{}
+{
+}
JniOcSecureResource::~JniOcSecureResource()
{
return ret;
}
+OCStackResult JniOcSecureResource::provisionDirectPairing(JNIEnv* env, jobjectArray jpdacls,
+ jobject jListener, std::string pin, std::vector<int> prms, int edp)
+{
+ OCStackResult ret;
+ JniProvisionResultListner *resultListener = AddProvisionResultListener(env, jListener);
+
+ jsize len = env->GetArrayLength(jpdacls);
+
+ OicSecPconf_t *pconf = nullptr;
+ OicSecPdAcl_t *head = nullptr;
+
+ for (jsize i = 0; i < len; ++i)
+ {
+ OicSecPdAcl_t *pdacl = new OicSecPdAcl_t;
+ if (!pdacl)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ memset(pdacl, 0, sizeof(OicSecPdAcl_t));
+ pdacl->next = nullptr;
+
+ jobject jpdacl = env->GetObjectArrayElement(jpdacls, i);
+
+ if (OC_STACK_OK != JniSecureUtils::convertJavaPdACLToOCAcl(env, jpdacl, pdacl))
+ {
+ delete pdacl;
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->next = head;
+ head = pdacl;
+ }
+
+ pconf = new OicSecPconf_t;
+ memset(pconf, 0, sizeof(OicSecPconf_t));
+ pconf->edp = edp;
+ pconf->prmLen = prms.size();
+ pconf->prm = new OicSecPrm_t[pconf->prmLen];
+ pconf->pddevLen = 0;
+
+ for (int i = 0 ; i < prms.size(); i++)
+ pconf->prm[i] = (OicSecPrm_t)prms[i];
+
+ memcpy(pconf->pin.val, pin.c_str(), DP_PIN_LENGTH);
+ pconf->pdacls = head;
+
+ ResultCallBack resultCallback = [head, resultListener, pconf, prms]
+ (PMResultList_t *result, int hasError)
+ {
+ OicSecPdAcl_t *tmp1, *tmp2;
+ tmp1 = head;
+ while (tmp1)
+ {
+ tmp2 = tmp1->next;
+ delete tmp1;
+ tmp1 = tmp2;
+ }
+
+ delete pconf->prm;
+ delete pconf;
+ resultListener->ProvisionResultCallback(result, hasError, ListenerFunc::PROVISIONDIRECTPAIRING);
+ };
+
+ ret = m_sharedSecureResource->provisionDirectPairing(pconf, resultCallback);
+
+ if (ret != OC_STACK_OK)
+ {
+ OicSecPdAcl_t *tmp1, *tmp2;
+ tmp1 = head;
+ while (tmp1)
+ {
+ tmp2 = tmp1->next;
+ delete tmp1;
+ tmp1 = tmp2;
+ }
+
+ delete pconf->prm;
+ delete pconf;
+ }
+ return ret;
+}
+
OCStackResult JniOcSecureResource::provisionPairwiseDevices(JNIEnv* env, jint type, jint keySize,
jobject _acl1, jobject _device2, jobject _acl2, jobject jListener)
{
/*
* Class: org_iotivity_base_OcSecureResource
+ * Method: provisionDirectPairing
+ * Signature: (Ljava/lang/String;[Lorg/iotivity/base/OicSecPdAcl;ILorg/iotivity/base/OcSecureResource/ProvisionDirectPairingListener;I)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionDirectPairing
+(JNIEnv *env, jobject thiz, jstring jpin, jobjectArray pdacls, jintArray jprmType,
+ jint jedp, jobject jListener)
+{
+ LOGD("OcSecureResource_provisionDirectPairing");
+ if (!jListener || !pdacls || !jpin || ! jprmType)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Invalid Parameters");
+ return;
+ }
+ std::string pin = env->GetStringUTFChars(jpin, nullptr);
+
+ JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
+ if (!secureResource)
+ {
+ return;
+ }
+
+ const jsize len = env->GetArrayLength(jprmType);
+ jint* ints = env->GetIntArrayElements(jprmType, nullptr);
+ std::vector<int> value;
+ for (jsize i = 0; i < len; ++i)
+ {
+ value.push_back(static_cast<int>(ints[i]));
+ }
+ env->ReleaseIntArrayElements(jprmType, ints, JNI_ABORT);
+
+ try
+ {
+ OCStackResult result = secureResource->provisionDirectPairing(env, pdacls, jListener,
+ pin, value, static_cast<int>(jedp));
+ if (OC_STACK_OK != result)
+ {
+ ThrowOcException(result, "OcSecureResource_provisionDirectPairing");
+ return;
+ }
+ }
+ catch (OCException& e)
+ {
+ LOGE("%s", e.reason().c_str());
+ ThrowOcException(e.code(), e.reason().c_str());
+ }
+}
+
+/*
+ * Class: org_iotivity_base_OcSecureResource
* Method: getLinkedDevices
* Signature: ()Ljava/util/List;
*/
jobject device2, jobject jListener);
OCStackResult unlinkDevices(JNIEnv* env, jobject device2, jobject jListener);
OCStackResult removeDevice(JNIEnv* env, jint timeout, jobject jListener);
-
+ OCStackResult provisionDirectPairing(JNIEnv* env, jobjectArray jpdacls,jobject jListener,
+ std::string pin, std::vector<int> prms, int edp);
private:
std::map<jobject, std::pair<JniProvisionResultListner*, int>> resultMap;
/*
* Class: org_iotivity_base_OcSecureResource
+ * Method: provisionDirectPairing
+ * Signature: (Ljava/lang/Object;Lorg/iotivity/base/OcSecureResource/ProvisionDirectPairingListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionDirectPairing
+ (JNIEnv *, jobject, jstring, jobjectArray, jintArray, jint, jobject);
+
+/*
+ * Class: org_iotivity_base_OcSecureResource
* Method: getLinkedDevices
* Signature: ()Ljava/util/List;
*/
#include "OCRepresentation.h"
#include "JniUtils.h"
+/**
+ * Macro to verify the validity of input argument.
+ *
+ * @param arg log level
+ */
+#define VERIFY_VARIABLE_NULL(arg) \
+ if (nullptr == (arg)) \
+ { \
+ LOGE("invalid input"); \
+ return JNI_ERR; \
+ } \
+
JavaVM* g_jvm = nullptr;
jclass g_cls_Integer = nullptr;
jclass g_cls_OcProvisionResult = nullptr;
jclass g_cls_OcSecureResource = nullptr;
jclass g_cls_OcOicSecAcl = nullptr;
+jclass g_cls_OcOicSecPdAcl = nullptr;
+jclass g_cls_OcDirectPairDevice = nullptr;
jmethodID g_mid_Integer_ctor = nullptr;
jmethodID g_mid_Double_ctor = nullptr;
jmethodID g_mid_OcResourceIdentifier_N_ctor = nullptr;
jmethodID g_mid_OcProvisionResult_ctor = nullptr;
jmethodID g_mid_OcSecureResource_ctor = nullptr;
+jmethodID g_mid_OcDirectPairDevice_ctor = nullptr;
+jmethodID g_mid_OcDirectPairDevice_dev_ctor = nullptr;
jmethodID g_mid_OcOicSecAcl_get_subject = nullptr;
jmethodID g_mid_OcOicSecAcl_get_resources_cnt = nullptr;
jmethodID g_mid_OcOicSecAcl_get_periods = nullptr;
jmethodID g_mid_OcOicSecAcl_get_recurrences = nullptr;
jmethodID g_mid_OcOicSecAcl_get_rownerID = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_resources_cnt = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_resources = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_permission = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_periods_cnt = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_periods = nullptr;
+jmethodID g_mid_OcOicSecPdAcl_get_recurrences = nullptr;
jobject getOcException(JNIEnv* env, const char* file, const char* functionName,
const int line, const int code, const char* message)
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
LOGI("JNI_OnLoad");
- JNIEnv* env;
+ JNIEnv* env = nullptr;
g_jvm = vm;
if (g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION) != JNI_OK)
LOGE("Failed to get the environment using GetEnv()");
return JNI_ERR;
}
+ VERIFY_VARIABLE_NULL(env);
jclass clazz = nullptr;
//Integer
clazz = env->FindClass("java/lang/Integer");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
+
g_cls_Integer = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Integer_ctor = env->GetMethodID(g_cls_Integer, "<init>", "(I)V");
- if (!g_mid_Integer_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Integer_ctor);
clazz = env->FindClass("[I");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_int1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[I");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_int2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//Double
clazz = env->FindClass("java/lang/Double");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Double = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Double_ctor = env->GetMethodID(g_cls_Double, "<init>", "(D)V");
- if (!g_mid_Double_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Double_ctor);
clazz = env->FindClass("[D");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_double1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[D");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_double2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//Boolean
clazz = env->FindClass("java/lang/Boolean");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Boolean = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Boolean_ctor = env->GetMethodID(g_cls_Boolean, "<init>", "(Z)V");
- if (!g_mid_Boolean_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Boolean_ctor);
clazz = env->FindClass("[Z");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_boolean1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[Z");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_boolean2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//String
clazz = env->FindClass("java/lang/String");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_String = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[Ljava/lang/String;");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_String1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[Ljava/lang/String;");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_String2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//LinkedList
clazz = env->FindClass("java/util/LinkedList");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_LinkedList = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_LinkedList_ctor = env->GetMethodID(g_cls_LinkedList, "<init>", "()V");
- if (!g_mid_LinkedList_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_LinkedList_ctor);
g_mid_LinkedList_add_object = env->GetMethodID(g_cls_LinkedList, "add", "(Ljava/lang/Object;)Z");
- if (!g_mid_LinkedList_add_object) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_LinkedList_add_object);
//Map
clazz = env->FindClass("java/util/Map");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Map = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Map_entrySet = env->GetMethodID(g_cls_Map, "entrySet", "()Ljava/util/Set;");
- if (!g_mid_Map_entrySet) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Map_entrySet);
//MapEntry
clazz = env->FindClass("java/util/Map$Entry");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_MapEntry = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_MapEntry_getKey = env->GetMethodID(g_cls_MapEntry, "getKey", "()Ljava/lang/Object;");
- if (!g_mid_MapEntry_getKey) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_MapEntry_getKey);
g_mid_MapEntry_getValue = env->GetMethodID(g_cls_MapEntry, "getValue", "()Ljava/lang/Object;");
- if (!g_mid_MapEntry_getValue) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_MapEntry_getValue);
//Set
clazz = env->FindClass("java/util/Set");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Set = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Set_iterator = env->GetMethodID(g_cls_Set, "iterator", "()Ljava/util/Iterator;");
- if (!g_mid_Set_iterator) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Set_iterator);
//Iterator
clazz = env->FindClass("java/util/Iterator");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_Iterator = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_Iterator_hasNext = env->GetMethodID(g_cls_Iterator, "hasNext", "()Z");
- if (!g_mid_Iterator_hasNext) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Iterator_hasNext);
g_mid_Iterator_next = env->GetMethodID(g_cls_Iterator, "next", "()Ljava/lang/Object;");
- if (!g_mid_Iterator_next) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_Iterator_next);
//HashMap
clazz = env->FindClass("java/util/HashMap");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_HashMap = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_HashMap_ctor = env->GetMethodID(g_cls_HashMap, "<init>", "()V");
- if (!g_mid_HashMap_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_HashMap_ctor);
g_mid_HashMap_put = env->GetMethodID(g_cls_HashMap, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
- if (!g_mid_HashMap_put) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_HashMap_put);
//OcException
clazz = env->FindClass("org/iotivity/base/OcException");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcException = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcException_ctor = env->GetMethodID(g_cls_OcException, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
- if (!g_mid_OcException_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcException_ctor);
g_mid_OcException_setNativeExceptionLocation = env->GetMethodID(g_cls_OcException, "setNativeExceptionLocation",
"(Ljava/lang/String;""Ljava/lang/String;""I)V");
- if (!g_mid_OcException_setNativeExceptionLocation) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcException_setNativeExceptionLocation);
//OcResource
clazz = env->FindClass("org/iotivity/base/OcResource");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResource = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResource_ctor = env->GetMethodID(g_cls_OcResource, "<init>", "(J)V");
- if (!g_mid_OcResource_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResource_ctor);
//OcRepresentation
clazz = env->FindClass("org/iotivity/base/OcRepresentation");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcRepresentation = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcRepresentation_N_ctor = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(J)V");
- if (!g_mid_OcRepresentation_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcRepresentation_N_ctor);
g_mid_OcRepresentation_N_ctor_bool = env->GetMethodID(g_cls_OcRepresentation, "<init>", "(JZ)V");
- if (!g_mid_OcRepresentation_N_ctor_bool) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcRepresentation_N_ctor_bool);
clazz = env->FindClass("[Lorg/iotivity/base/OcRepresentation;");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcRepresentation1DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
clazz = env->FindClass("[[Lorg/iotivity/base/OcRepresentation;");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcRepresentation2DArray = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
//HeaderOptions
clazz = env->FindClass("org/iotivity/base/OcHeaderOption");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcHeaderOption = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcHeaderOption_ctor = env->GetMethodID(g_cls_OcHeaderOption, "<init>", "(ILjava/lang/String;)V");
- if (!g_mid_OcHeaderOption_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_ctor);
g_mid_OcHeaderOption_get_id = env->GetMethodID(g_cls_OcHeaderOption, "getOptionId", "()I");
- if (!g_mid_OcHeaderOption_get_id) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_get_id);
g_mid_OcHeaderOption_get_data = env->GetMethodID(g_cls_OcHeaderOption, "getOptionData", "()Ljava/lang/String;");
- if (!g_mid_OcHeaderOption_get_data) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcHeaderOption_get_data);
//OcResourceRequest
clazz = env->FindClass("org/iotivity/base/OcResourceRequest");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResourceRequest = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResourceRequest_N_ctor = env->GetMethodID(g_cls_OcResourceRequest, "<init>", "(J)V");
- if (!g_mid_OcResourceRequest_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResourceRequest_N_ctor);
//OcResourceResponse
clazz = env->FindClass("org/iotivity/base/OcResourceResponse");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResourceResponse = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResourceResponse_N_ctor = env->GetMethodID(g_cls_OcResourceResponse, "<init>", "(J)V");
- if (!g_mid_OcResourceResponse_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResourceResponse_N_ctor);
//OcResourceHandle
clazz = env->FindClass("org/iotivity/base/OcResourceHandle");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResourceHandle = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResourceHandle_N_ctor = env->GetMethodID(g_cls_OcResourceHandle, "<init>", "(J)V");
- if (!g_mid_OcResourceHandle_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResourceHandle_N_ctor);
//OcPresenceHandle
clazz = env->FindClass("org/iotivity/base/OcPresenceHandle");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcPresenceHandle = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcPresenceHandle_N_ctor = env->GetMethodID(g_cls_OcPresenceHandle, "<init>", "(J)V");
- if (!g_mid_OcPresenceHandle_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcPresenceHandle_N_ctor);
//OcRequestHandle
clazz = env->FindClass("org/iotivity/base/OcRequestHandle");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcRequestHandle = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcRequestHandle_N_ctor = env->GetMethodID(g_cls_OcRequestHandle, "<init>", "(J)V");
- if (!g_mid_OcRequestHandle_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcRequestHandle_N_ctor);
//OcPresenceStatus
clazz = env->FindClass("org/iotivity/base/OcPresenceStatus");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcPresenceStatus = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcPresenceStatus_get = env->GetStaticMethodID(g_cls_OcPresenceStatus, "get",
"(Ljava/lang/String;)Lorg/iotivity/base/OcPresenceStatus;");
- if (!g_mid_OcPresenceStatus_get) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcPresenceStatus_get);
//ObservationInfo
clazz = env->FindClass("org/iotivity/base/ObservationInfo");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_ObservationInfo = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_ObservationInfo_N_ctor = env->GetMethodID(g_cls_ObservationInfo, "<init>", "(IB)V");
- if (!g_mid_ObservationInfo_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_ObservationInfo_N_ctor);
clazz = env->FindClass("org/iotivity/base/OcResourceIdentifier");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcResourceIdentifier = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcResourceIdentifier_N_ctor = env->GetMethodID(g_cls_OcResourceIdentifier, "<init>", "(J)V");
- if (!g_mid_OcResourceIdentifier_N_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcResourceIdentifier_N_ctor);
//OcSecureResource
clazz = env->FindClass("org/iotivity/base/OcSecureResource");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcSecureResource = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcSecureResource_ctor = env->GetMethodID(g_cls_OcSecureResource, "<init>", "(J)V");
- if (!g_mid_OcSecureResource_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcSecureResource_ctor);
//ProvisionResult
clazz = env->FindClass("org/iotivity/base/ProvisionResult");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcProvisionResult = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcProvisionResult_ctor = env->GetMethodID(g_cls_OcProvisionResult, "<init>", "(Ljava/lang/String;I)V");
- if (!g_mid_OcProvisionResult_ctor) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcProvisionResult_ctor);
+
+ //OcDirectPairDevice
+ clazz = env->FindClass("org/iotivity/base/OcDirectPairDevice");
+ VERIFY_VARIABLE_NULL(clazz);
+ g_cls_OcDirectPairDevice = (jclass)env->NewGlobalRef(clazz);
+ g_mid_OcDirectPairDevice_ctor = env->GetMethodID(g_cls_OcDirectPairDevice, "<init>", "(J)V");
+ VERIFY_VARIABLE_NULL(g_mid_OcDirectPairDevice_ctor);
+
+ g_mid_OcDirectPairDevice_dev_ctor = env->GetMethodID(g_cls_OcDirectPairDevice, "<init>", "(Ljava/lang/String;)V");
+ VERIFY_VARIABLE_NULL(g_mid_OcDirectPairDevice_dev_ctor);
+ env->DeleteLocalRef(clazz);
//OicSecAcl
clazz = env->FindClass("org/iotivity/base/OicSecAcl");
- if (!clazz) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(clazz);
g_cls_OcOicSecAcl = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
g_mid_OcOicSecAcl_get_subject = env->GetMethodID(g_cls_OcOicSecAcl, "getSubject", "()Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_subject) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_subject);
g_mid_OcOicSecAcl_get_resources_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getResourcesCount", "()I");
- if (!g_mid_OcOicSecAcl_get_resources_cnt) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_resources_cnt);
g_mid_OcOicSecAcl_get_resources = env->GetMethodID(g_cls_OcOicSecAcl, "getResources", "(I)Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_resources) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_resources);
g_mid_OcOicSecAcl_get_permission = env->GetMethodID(g_cls_OcOicSecAcl, "getPermission", "()I");
- if (!g_mid_OcOicSecAcl_get_permission) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_permission);
g_mid_OcOicSecAcl_get_periods_cnt = env->GetMethodID(g_cls_OcOicSecAcl, "getPeriodsCount", "()I");
- if (!g_mid_OcOicSecAcl_get_periods_cnt) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_periods_cnt);
g_mid_OcOicSecAcl_get_periods = env->GetMethodID(g_cls_OcOicSecAcl, "getPeriods", "(I)Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_periods) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_periods);
g_mid_OcOicSecAcl_get_recurrences = env->GetMethodID(g_cls_OcOicSecAcl, "getRecurrences", "(I)Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_recurrences) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_recurrences);
g_mid_OcOicSecAcl_get_rownerID = env->GetMethodID(g_cls_OcOicSecAcl, "getRownerID", "()Ljava/lang/String;");
- if (!g_mid_OcOicSecAcl_get_rownerID) return JNI_ERR;
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecAcl_get_rownerID);
+
+ //OicSecPdAcl
+ clazz = env->FindClass("org/iotivity/base/OicSecPdAcl");
+ VERIFY_VARIABLE_NULL(clazz);
+ g_cls_OcOicSecPdAcl = (jclass)env->NewGlobalRef(clazz);
+ env->DeleteLocalRef(clazz);
+
+ g_mid_OcOicSecPdAcl_get_resources_cnt = env->GetMethodID(g_cls_OcOicSecPdAcl, "getResourcesCount", "()I");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_resources_cnt);
+
+ g_mid_OcOicSecPdAcl_get_resources = env->GetMethodID(g_cls_OcOicSecPdAcl, "getResources", "(I)Ljava/lang/String;");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_resources);
+
+ g_mid_OcOicSecPdAcl_get_permission = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPermission", "()I");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_permission);
+
+ g_mid_OcOicSecPdAcl_get_periods_cnt = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPeriodsCount", "()I");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_periods_cnt);
+
+ g_mid_OcOicSecPdAcl_get_periods = env->GetMethodID(g_cls_OcOicSecPdAcl, "getPeriods", "(I)Ljava/lang/String;");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_periods);
+
+ g_mid_OcOicSecPdAcl_get_recurrences = env->GetMethodID(g_cls_OcOicSecPdAcl, "getRecurrences", "(I)Ljava/lang/String;");
+ VERIFY_VARIABLE_NULL(g_mid_OcOicSecPdAcl_get_recurrences);
return JNI_CURRENT_VERSION;
}
return;
}
+
env->DeleteGlobalRef(g_cls_Integer);
env->DeleteGlobalRef(g_cls_int1DArray);
env->DeleteGlobalRef(g_cls_int2DArray);
env->DeleteGlobalRef(g_cls_OcSecureResource);
env->DeleteGlobalRef(g_cls_OcProvisionResult);
env->DeleteGlobalRef(g_cls_OcOicSecAcl);
-}
\ No newline at end of file
+}
extern jclass g_cls_OcProvisionResult;
extern jclass g_cls_OcSecureResource;
extern jclass g_cls_OcOicSecAcl;
+extern jclass g_cls_OcOicSecPdAcl;
+extern jclass g_cls_OcDirectPairDevice;
extern jmethodID g_mid_Integer_ctor;
extern jmethodID g_mid_Double_ctor;
extern jmethodID g_mid_OcResourceIdentifier_N_ctor;
extern jmethodID g_mid_OcProvisionResult_ctor;
extern jmethodID g_mid_OcSecureResource_ctor;
+extern jmethodID g_mid_OcDirectPairDevice_ctor;
+extern jmethodID g_mid_OcDirectPairDevice_dev_ctor;
extern jmethodID g_mid_OcOicSecAcl_get_subject;
extern jmethodID g_mid_OcOicSecAcl_get_resources_cnt;
extern jmethodID g_mid_OcOicSecAcl_get_resources;
extern jmethodID g_mid_OcOicSecAcl_get_periods;
extern jmethodID g_mid_OcOicSecAcl_get_recurrences;
extern jmethodID g_mid_OcOicSecAcl_get_rownerID;
+extern jmethodID g_mid_OcOicSecPdAcl_get_resources_cnt;
+extern jmethodID g_mid_OcOicSecPdAcl_get_resources;
+extern jmethodID g_mid_OcOicSecPdAcl_get_permission;
+extern jmethodID g_mid_OcOicSecPdAcl_get_periods_cnt;
+extern jmethodID g_mid_OcOicSecPdAcl_get_periods;
+extern jmethodID g_mid_OcOicSecPdAcl_get_recurrences;
typedef void(*RemoveListenerCallback)(JNIEnv* env, jobject jListener);
JNIEnv *env = nullptr;
ret = g_jvm->GetEnv((void **)&env, JNI_CURRENT_VERSION);
- switch (ret) {
- case JNI_OK:
- return env;
- case JNI_EDETACHED:
- if (g_jvm->AttachCurrentThread(&env, nullptr) < 0)
- {
+ switch (ret)
+ {
+ case JNI_OK:
+ return env;
+ case JNI_EDETACHED:
+ if (g_jvm->AttachCurrentThread(&env, nullptr) < 0)
+ {
+ LOGE("Failed to get the environment");
+ return nullptr;
+ }
+ else
+ {
+ return env;
+ }
+
+ case JNI_EVERSION:
+ LOGE("JNI version not supported");
+ break;
+ default:
LOGE("Failed to get the environment");
return nullptr;
- }
- else
- {
- return env;
- }
-
- case JNI_EVERSION:
- LOGE("JNI version not supported");
- default:
- LOGE("Failed to get the environment");
- return nullptr;
}
+ return nullptr;
}
static void DuplicateString(char ** targetString, std::string sourceString)
strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
}
-#endif // _Included_org_iotivity_base_ocstack
\ No newline at end of file
+#endif // _Included_org_iotivity_base_ocstack
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // Copyright 2016 Samsung Electronics All Rights Reserved.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* // http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include "JniOnDPDevicesFoundListener.h"
+#include "JniOcDirectPairDevice.h"
+#include "OCApi.h"
+using namespace OC;
+
+JniOnDPDevicesFoundListener::JniOnDPDevicesFoundListener(JNIEnv *env, jobject jListener,
+ RemoveListenerCallback removeListenerCallback)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+ m_removeListenerCallback = removeListenerCallback;
+}
+
+jobject JniOnDPDevicesFoundListener::convertdpDevVectorToJavaList(JNIEnv *env, PairedDevices DPdevList)
+{
+ jobject jResultList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
+ if (!jResultList)
+ {
+ return nullptr;
+ }
+
+ for (size_t i = 0; i < DPdevList.size(); ++i)
+ {
+ JniOcDirectPairDevice *device = new JniOcDirectPairDevice(DPdevList.at(i));
+ if (!device)
+ {
+ return nullptr;
+ }
+
+ jstring jStr = env->NewStringUTF(((DPdevList.at(i))->getDeviceID()).c_str());
+ if (!jStr)
+ {
+ return nullptr;
+ }
+ jobject jresult = env->NewObject(g_cls_OcDirectPairDevice,
+ g_mid_OcDirectPairDevice_dev_ctor,jStr);
+ if (!jresult)
+ {
+ return nullptr;
+ }
+
+ SetHandle<JniOcDirectPairDevice>(env, jresult, device);
+
+ env->CallBooleanMethod(jResultList, g_mid_LinkedList_add_object, jresult);
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
+ env->DeleteLocalRef(jresult);
+ env->DeleteLocalRef(jStr);
+ }
+ return jResultList;
+}
+
+JniOnDPDevicesFoundListener::~JniOnDPDevicesFoundListener()
+{
+ LOGI("~JniOnDPDevicesFoundListener()");
+ if (m_jwListener)
+ {
+ jint ret = JNI_ERR;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+ env->DeleteWeakGlobalRef(m_jwListener);
+ m_jwListener = nullptr;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ }
+}
+
+void JniOnDPDevicesFoundListener::directPairingDevicesCallback(PairedDevices paringDevicesList, DPFunc func)
+{
+ jint ret;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jobject jpairingDevicesList = convertdpDevVectorToJavaList(env, paringDevicesList);
+ std::string calledFunc;
+ switch (func)
+ {
+ case DPFunc::FIND_DIRECT_PAIRED_DEV_LIST:
+ {
+ calledFunc = "onFindDirectPairingListener";
+ }
+ break;
+ case DPFunc::GET_PAIRED_DEV_LIST:
+ {
+ calledFunc = "onGetDirectPairedListener";
+ }
+ break;
+ default:
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ }
+ return;
+ }
+
+ jmethodID midL = env->GetMethodID(clsL, calledFunc.c_str(), "(Ljava/util/List;)V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ env->CallVoidMethod(jListener, midL, jpairingDevicesList);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Java exception is thrown");
+ }
+
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniOnDPDevicesFoundListener::checkExAndRemoveListener(JNIEnv* env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_removeListenerCallback(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_removeListenerCallback(env, m_jwListener);
+ }
+}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // Copyright 2016 Samsung Electronics All Rights Reserved.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* // http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include <jni.h>
+#include "OCDirectPairing.h"
+#include "OCApi.h"
+#include "JniOcStack.h"
+
+#ifndef _Included_org_iotivity_base_OcPlatform_JniOnDPDevicesFoundListener
+#define _Included_org_iotivity_base_OcPlatform_JniOnDPDevicesFoundListener
+
+enum class DPFunc
+{
+ FIND_DIRECT_PAIRED_DEV_LIST = 1,
+ GET_PAIRED_DEV_LIST,
+};
+
+class JniOnDPDevicesFoundListener
+{
+public:
+ JniOnDPDevicesFoundListener(JNIEnv *env, jobject jListener,
+ RemoveListenerCallback removeListenerCallback);
+ ~JniOnDPDevicesFoundListener();
+
+ jobject convertdpDevVectorToJavaList(JNIEnv *env, OC::PairedDevices DPdevList);
+ void directPairingDevicesCallback(OC::PairedDevices paringDevicesList, DPFunc);
+
+private:
+ RemoveListenerCallback m_removeListenerCallback;
+ jweak m_jwListener;
+ void checkExAndRemoveListener(JNIEnv* env);
+};
+#endif
{
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
-
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, const int eCode)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onDeleteFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, jHeaderOptionList);
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnDeleteListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnDeleteListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGI("~JniOnDeviceInfoListener");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& ocRepresentation)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
LOGI("Java onDeviceInfoListener object is already destroyed, quiting");
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onDeviceFound", "(Lorg/iotivity/base/OcRepresentation;)V");
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
checkExAndRemoveListener(env);
}
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnDeviceInfoListener::checkExAndRemoveListener(JNIEnv* env)
{
m_removeListenerCallback(env, m_jwListener);
}
-}
\ No newline at end of file
+}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // Copyright 2016 Samsung Electronics All Rights Reserved.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* // http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include "JniOnDirectPairingListener.h"
+#include "JniOcDirectPairDevice.h"
+#include "OCDirectPairing.h"
+#include "OCApi.h"
+using namespace OC;
+
+JniOnDirectPairingListener::JniOnDirectPairingListener(JNIEnv *env, jobject jListener,
+ RemoveListenerCallback removeListenerCallback)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+ m_removeListenerCallback = removeListenerCallback;
+}
+
+
+JniOnDirectPairingListener::~JniOnDirectPairingListener()
+{
+ LOGI("~JniOnDirectPairingListener()");
+ if (m_jwListener)
+ {
+ jint ret = JNI_ERR;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+ env->DeleteWeakGlobalRef(m_jwListener);
+ m_jwListener = nullptr;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ }
+}
+
+void JniOnDirectPairingListener::doDirectPairingCB(std::shared_ptr<OC::OCDirectPairing> dpDev,
+ OCStackResult result)
+{
+ jint ret = JNI_ERR;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jclass clsL = env->GetObjectClass(jListener);
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ JniOcDirectPairDevice *device = new JniOcDirectPairDevice(dpDev);
+ if (!device)
+ {
+ return;
+ }
+
+ jstring jStr = env->NewStringUTF((dpDev->getDeviceID()).c_str());
+ if (!jStr)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ jobject jresult = env->NewObject(g_cls_OcDirectPairDevice, g_mid_OcDirectPairDevice_ctor);
+ if (!jresult)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ SetHandle<JniOcDirectPairDevice>(env, jresult, device);
+
+ jint jres = static_cast<jint>(result);
+
+ jmethodID midL = env->GetMethodID(clsL, "onDirectPairingListener", "(Ljava/lang/String;I)V");
+
+ if (!midL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ env->CallVoidMethod(jListener, midL, jStr, jres);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Java exception is thrown");
+ }
+
+ checkExAndRemoveListener(env);
+
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniOnDirectPairingListener::checkExAndRemoveListener(JNIEnv* env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_removeListenerCallback(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_removeListenerCallback(env, m_jwListener);
+ }
+}
--- /dev/null
+/*
+* //******************************************************************
+* //
+* // Copyright 2016 Samsung Electronics All Rights Reserved.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // Licensed under the Apache License, Version 2.0 (the "License");
+* // you may not use this file except in compliance with the License.
+* // You may obtain a copy of the License at
+* //
+* // http://www.apache.org/licenses/LICENSE-2.0
+* //
+* // Unless required by applicable law or agreed to in writing, software
+* // distributed under the License is distributed on an "AS IS" BASIS,
+* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* // See the License for the specific language governing permissions and
+* // limitations under the License.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include <jni.h>
+#include "OCDirectPairing.h"
+#include "JniOcStack.h"
+
+#ifndef _Included_org_iotivity_base_OcPlatform_JniOnDirectPairingListener
+#define _Included_org_iotivity_base_OcPlatform_JniOnDirectPairingListener
+
+class JniOnDirectPairingListener
+{
+public:
+ JniOnDirectPairingListener(JNIEnv *env, jobject jListener,
+ RemoveListenerCallback removeListenerCallback);
+ ~JniOnDirectPairingListener();
+
+ void doDirectPairingCB(std::shared_ptr<OC::OCDirectPairing>, OCStackResult);
+
+private:
+ RemoveListenerCallback m_removeListenerCallback;
+ jweak m_jwListener;
+ void checkExAndRemoveListener(JNIEnv* env);
+};
+#endif
LOGD("~JniOnGetListener");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
const OCRepresentation& ocRepresentation, const int eCode)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onGetFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, jHeaderOptionList, jRepresentation);
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnGetListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnGetListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
{
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
const OCRepresentation& ocRepresentation, const int& eCode, const int& sequenceNumber)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onObserveFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
}
}
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnObserveListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnObserveListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGI("~JniOnPlatformInfoListener");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation& ocRepresentation)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
LOGI("Java onPlatformInfoListener object is already destroyed, quiting");
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onPlatformFound", "(Lorg/iotivity/base/OcRepresentation;)V");
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
checkExAndRemoveListener(env);
}
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnPlatformInfoListener::checkExAndRemoveListener(JNIEnv* env)
{
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
const OCRepresentation& ocRepresentation, const int eCode)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onPostFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnPostListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnPostListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGD("~JniOnPresenceListener");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
const std::string& hostAddress)
{
LOGI("JniOnPresenceListener::onPresenceCallback");
- if (!m_jwListener) return;
+ if (!m_jwListener)
+ {
+ return;
+ }
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
if (OC_STACK_OK != result && OC_STACK_PRESENCE_STOPPED != result &&
OC_STACK_PRESENCE_TIMEOUT != result && OC_STACK_PRESENCE_DO_NOT_HANDLE != result)
{
ThrowOcException(result, "onPresenceCallback: stack failure");
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (enumField.empty())
{
ThrowOcException(JNI_INVALID_VALUE, "Unexpected OCStackResult value");
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!jPresenceStatus)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onPresence",
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
LOGE("Java exception is thrown");
checkExAndRemoveListener(env);
}
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnPresenceListener::checkExAndRemoveListener(JNIEnv* env)
jweak JniOnPresenceListener::getJWListener()
{
return this->m_jwListener;
-}
\ No newline at end of file
+}
{
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
const OCRepresentation& ocRepresentation, const int eCode)
{
- jint envRet;
+ jint envRet = JNI_ERR;
JNIEnv *env = GetJNIEnv(envRet);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!ex)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "onPutFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, ex);
if (!jHeaderOptionList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
{
delete rep;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnPutListener::checkExAndRemoveListener(JNIEnv* env)
{
m_ownerResource->removeOnPutListener(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGI("~JniOnResourceFoundListener()");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
m_jwListener = nullptr;
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCResource> resource)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (nullptr == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
jobject jResource = env->NewObject(g_cls_OcResource, g_mid_OcResource_ctor);
if (!jResource)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
JniOcResource *jniOcResource = new JniOcResource(resource);
{
delete jniOcResource;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
jclass clsL = env->GetObjectClass(jListener);
if (!clsL)
{
delete jniOcResource;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
jmethodID midL = env->GetMethodID(clsL, "onResourceFound", "(Lorg/iotivity/base/OcResource;)V");
if (!midL)
{
delete jniOcResource;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
env->CallVoidMethod(jListener, midL, jResource);
if (env->ExceptionCheck())
LOGE("Java exception is thrown");
delete jniOcResource;
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
- return;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniOnResourceFoundListener::checkExAndRemoveListener(JNIEnv* env)
{
m_removeListenerCallback(env, m_jwListener);
}
-}
\ No newline at end of file
+}
LOGI("~JniPinCheckListener()");
if (m_jListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteGlobalRef(m_jListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniPinCheckListener::PinCallback(char *pinBuf, size_t bufSize)
{
- jint ret;
-
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jclass clsL = env->GetObjectClass(m_jListener);
if (!clsL)
{
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jmethodID midL = env->GetMethodID(clsL, "pinCallbackListener", "()Ljava/lang/String;");
if (!midL)
{
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
jstring jpin = (jstring)env->CallObjectMethod(m_jListener, midL);
if (env->ExceptionCheck())
{
LOGE("Java exception is thrown");
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
OICStrcpy(pinBuf, bufSize, str);
env->ReleaseStringUTFChars(jpin, str);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
LOGI("~JniProvisionResultListner()");
if (m_jwListener)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
env->DeleteWeakGlobalRef(m_jwListener);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
}
void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result, int hasError,
ListenerFunc func)
{
- jint ret;
+ jint ret = JNI_ERR;
JNIEnv *env = GetJNIEnv(ret);
- if (NULL == env) return;
+ if (nullptr == env)
+ {
+ return;
+ }
jobject jListener = env->NewLocalRef(m_jwListener);
if (!jListener)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!clsL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
if (!jResultList)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
calledFunc = "provisionPairwiseDevicesListener";
}
break;
+ case ListenerFunc::PROVISIONDIRECTPAIRING:
+ {
+ calledFunc = "provisionDirectPairingListener";
+ }
+ break;
default:
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
}
return;
}
if (!midL)
{
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
return;
}
env->CallVoidMethod(jListener, midL, jResultList, (jint)hasError);
}
checkExAndRemoveListener(env);
- if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
}
void JniProvisionResultListner::checkExAndRemoveListener(JNIEnv* env)
PROVISIONCREDENTIALS,
UNLINKDEVICES,
REMOVEDEVICE,
- PROVISIONPAIRWISEDEVICES
+ PROVISIONPAIRWISEDEVICES,
+ PROVISIONDIRECTPAIRING
};
class JniProvisionResultListner
return OC_STACK_OK;
}
+
+OCStackResult JniSecureUtils::convertJavaPdACLToOCAcl(JNIEnv *env, jobject in, OicSecPdAcl_t *pdacl)
+{
+ jstring jData;
+ jvalue args[1];
+
+ jint jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_resources_cnt);
+ if (!jCount || env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->resourcesLen = jCount;
+ pdacl->resources = new char*[jCount];
+
+ if (!pdacl->resources)
+ {
+ return OC_STACK_ERROR;
+ }
+ for (jint i = 0; i < jCount; ++i)
+ {
+ args[0].i = i;
+ jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_resources, args);
+ if (!jData || env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->resources[i] = (char*) env->GetStringUTFChars(jData, 0);
+ }
+
+ jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_permission);
+ if (env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->permission = jCount;
+ jCount = (jint) env->CallIntMethod(in, g_mid_OcOicSecPdAcl_get_periods_cnt);
+ if (env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->prdRecrLen = jCount;
+ if (jCount)
+ {
+ pdacl->periods = new char*[jCount];
+ if (!pdacl->periods)
+ {
+ return OC_STACK_ERROR;
+ }
+ }
+ for (jint i = 0; i < jCount; ++i)
+ {
+ args[0].i = i;
+ jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_periods, args);
+ if (!jData || env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->periods[i] = (char*) env->GetStringUTFChars(jData, 0);
+ }
+
+ if (jCount)
+ {
+ pdacl->recurrences = new char*[jCount];
+ if (!pdacl->recurrences)
+ {
+ return OC_STACK_ERROR;
+ }
+ }
+ for (jint i = 0; i < jCount; ++i)
+ {
+ args[0].i = i;
+ jData = (jstring) env->CallObjectMethodA(in, g_mid_OcOicSecPdAcl_get_recurrences, args);
+ if (!jData || env->ExceptionCheck())
+ {
+ return OC_STACK_ERROR;
+ }
+
+ pdacl->recurrences[i] = (char*) env->GetStringUTFChars(jData, 0);
+ }
+ return OC_STACK_OK;
+}
std::vector<std::shared_ptr<OC::OCSecureResource>>& deviceListVector);
static jobject convertUUIDVectorToJavaStrList(JNIEnv *env, OC::UuidList_t &vector);
static OCStackResult convertJavaACLToOCAcl(JNIEnv *env, jobject in, OicSecAcl_t *out);
+ static OCStackResult convertJavaPdACLToOCAcl(JNIEnv *env, jobject in, OicSecPdAcl_t *pdacl);
};
jobject JniUtils::convertStrVectorToJavaStrList(JNIEnv *env, std::vector<std::string> &vector)
{
jobject jList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
- if (!jList) return nullptr;
+ if (!jList)
+ {
+ return nullptr;
+ }
for (size_t i = 0; i < vector.size(); ++i)
{
jstring jStr = env->NewStringUTF(vector[i].c_str());
- if (!jStr) return nullptr;
+ if (!jStr)
+ {
+ return nullptr;
+ }
env->CallBooleanMethod(jList, g_mid_LinkedList_add_object, jStr);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jStr);
}
return jList;
void JniUtils::convertJavaStrArrToStrVector(JNIEnv *env, jobjectArray jStrArr, std::vector<std::string> &vector)
{
- if (!jStrArr) return;
+ if (!jStrArr)
+ {
+ return;
+ }
jsize len = env->GetArrayLength(jStrArr);
for (jsize i = 0; i < len; ++i)
{
jstring jStr = (jstring)env->GetObjectArrayElement(jStrArr, i);
- if (!jStr) return;
+ if (!jStr)
+ {
+ return;
+ }
vector.push_back(env->GetStringUTFChars(jStr, nullptr));
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ return;
+ }
env->DeleteLocalRef(jStr);
}
}
void JniUtils::convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHeaderOptions,
OC::HeaderOptions &headerOptions)
{
- if (!jHeaderOptions) return;
+ if (!jHeaderOptions)
+ {
+ return;
+ }
+
jsize len = env->GetArrayLength(jHeaderOptions);
for (jsize i = 0; i < len; ++i)
{
jobject header = env->GetObjectArrayElement(jHeaderOptions, i);
- if (!header) return;
+ if (!header)
+ {
+ return;
+ }
jint jId = env->CallIntMethod(header, g_mid_OcHeaderOption_get_id);
jstring jData = (jstring)env->CallObjectMethod(header, g_mid_OcHeaderOption_get_data);
OC::HeaderOption::OCHeaderOption hopt(
headerOptions.push_back(hopt);
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ return;
+ }
env->DeleteLocalRef(header);
env->DeleteLocalRef(jData);
}
jobject JniUtils::convertHeaderOptionsVectorToJavaList(JNIEnv *env, const OC::HeaderOptions& headerOptions)
{
jobject jHeaderOptionList = env->NewObject(g_cls_LinkedList, g_mid_LinkedList_ctor);
- if (!jHeaderOptionList) return nullptr;
+ if (!jHeaderOptionList)
+ {
+ return nullptr;
+ }
for (size_t i = 0; i < headerOptions.size(); ++i)
{
static_cast<jint>(headerOptions[i].getOptionID()),
env->NewStringUTF(headerOptions[i].getOptionData().c_str())
);
- if (!jHeaderOption) return nullptr;
+ if (!jHeaderOption)
+ {
+ return nullptr;
+ }
env->CallBooleanMethod(jHeaderOptionList, g_mid_LinkedList_add_object, jHeaderOption);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jHeaderOption);
}
void JniUtils::convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap, OC::QueryParamsMap &map)
{
- if (!hashMap) return;
+ if (!hashMap)
+ {
+ return;
+ }
jobject jEntrySet = env->CallObjectMethod(hashMap, g_mid_Map_entrySet);
jobject jIterator = env->CallObjectMethod(jEntrySet, g_mid_Set_iterator);
- if (!jEntrySet || !jIterator || env->ExceptionCheck()) return;
+ if (!jEntrySet || !jIterator || env->ExceptionCheck())
+ {
+ return;
+ }
while (env->CallBooleanMethod(jIterator, g_mid_Iterator_hasNext))
{
jobject jEntry = env->CallObjectMethod(jIterator, g_mid_Iterator_next);
- if (!jEntry) return;
+ if (!jEntry)
+ {
+ return;
+ }
jstring jKey = (jstring)env->CallObjectMethod(jEntry, g_mid_MapEntry_getKey);
- if (!jKey) return;
+ if (!jKey)
+ {
+ return;
+ }
jstring jValue = (jstring)env->CallObjectMethod(jEntry, g_mid_MapEntry_getValue);
- if (!jValue) return;
+ if (!jValue)
+ {
+ return;
+ }
map.insert(std::make_pair(env->GetStringUTFChars(jKey, nullptr),
env->GetStringUTFChars(jValue, nullptr)));
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ return;
+ }
env->DeleteLocalRef(jEntry);
env->DeleteLocalRef(jKey);
env->DeleteLocalRef(jValue);
jobject JniUtils::convertQueryParamsMapToJavaMap(JNIEnv *env, const OC::QueryParamsMap &map)
{
jobject hashMap = env->NewObject(g_cls_HashMap, g_mid_HashMap_ctor);
- if (!hashMap) return nullptr;
+ if (!hashMap)
+ {
+ return nullptr;
+ }
for (auto it = map.begin(); it != map.end(); ++it)
{
g_mid_HashMap_put,
env->NewStringUTF(key.c_str()),
env->NewStringUTF(value.c_str()));
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
}
return hashMap;
jobjectArray jRepresentationArray,
std::vector<OC::OCRepresentation>& representationVector)
{
- if (!jRepresentationArray) return;
+ if (!jRepresentationArray)
+ {
+ return;
+ }
jsize len = env->GetArrayLength(jRepresentationArray);
for (jsize i = 0; i < len; ++i)
{
jobject jRep = env->GetObjectArrayElement(jRepresentationArray, i);
- if (!jRep) return;
+ if (!jRep)
+ {
+ return;
+ }
OC::OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, jRep);
representationVector.push_back(*rep);
- if (env->ExceptionCheck()) return;
+ if (env->ExceptionCheck())
+ {
+ return;
+ }
env->DeleteLocalRef(jRep);
}
}
{
jsize len = static_cast<jsize>(representationVector.size());
jobjectArray repArr = env->NewObjectArray(len, g_cls_OcRepresentation, nullptr);
- if (!repArr) return nullptr;
+ if (!repArr)
+ {
+ return nullptr;
+ }
for (jsize i = 0; i < len; ++i)
{
OCRepresentation* rep = new OCRepresentation(representationVector[i]);
return nullptr;
}
env->SetObjectArrayElement(repArr, i, jRepresentation);
- if (env->ExceptionCheck()) return nullptr;
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
env->DeleteLocalRef(jRepresentation);
}
return repArr;
-}
\ No newline at end of file
+}
static OC::ServiceType getServiceType(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OC::ServiceType::InProc;
- case 1:
- return OC::ServiceType::OutOfProc;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected service type");
- return OC::ServiceType::OutOfProc;
+ switch (type)
+ {
+ case 0:
+ return OC::ServiceType::InProc;
+ case 1:
+ return OC::ServiceType::OutOfProc;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected service type");
+ return OC::ServiceType::OutOfProc;
};
}
static OC::ModeType getModeType(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OC::ModeType::Server;
- case 1:
- return OC::ModeType::Client;
- case 2:
- return OC::ModeType::Both;
- case 3:
- return OC::ModeType::Gateway;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected mode type");
- return OC::ModeType::Both;
+ switch (type)
+ {
+ case 0:
+ return OC::ModeType::Server;
+ case 1:
+ return OC::ModeType::Client;
+ case 2:
+ return OC::ModeType::Both;
+ case 3:
+ return OC::ModeType::Gateway;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected mode type");
+ return OC::ModeType::Both;
};
}
static OC::QualityOfService getQOS(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OC::QualityOfService::LowQos;
- case 1:
- return OC::QualityOfService::MidQos;
- case 2:
- return OC::QualityOfService::HighQos;
- case 3:
- return OC::QualityOfService::NaQos;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected quality of service");
- return OC::QualityOfService::NaQos;
+ switch (type)
+ {
+ case 0:
+ return OC::QualityOfService::LowQos;
+ case 1:
+ return OC::QualityOfService::MidQos;
+ case 2:
+ return OC::QualityOfService::HighQos;
+ case 3:
+ return OC::QualityOfService::NaQos;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected quality of service");
+ return OC::QualityOfService::NaQos;
};
}
static OC::ObserveType getObserveType(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OC::ObserveType::Observe;
- case 1:
- return OC::ObserveType::ObserveAll;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected observe type");
- return OC::ObserveType::ObserveAll;
+ switch (type)
+ {
+ case 0:
+ return OC::ObserveType::Observe;
+ case 1:
+ return OC::ObserveType::ObserveAll;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected observe type");
+ return OC::ObserveType::ObserveAll;
};
}
static OCEntityHandlerResult getOCEntityHandlerResult(JNIEnv *env, int type)
{
- switch (type) {
- case 0:
- return OCEntityHandlerResult::OC_EH_OK;
- case 1:
- return OCEntityHandlerResult::OC_EH_ERROR;
- case 2:
- return OCEntityHandlerResult::OC_EH_RESOURCE_CREATED;
- case 3:
- return OCEntityHandlerResult::OC_EH_RESOURCE_DELETED;
- case 4:
- return OCEntityHandlerResult::OC_EH_SLOW;
- case 5:
- return OCEntityHandlerResult::OC_EH_FORBIDDEN;
- case 6:
- return OCEntityHandlerResult::OC_EH_RESOURCE_NOT_FOUND;
- default:
- ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected OCEntityHandlerResult");
- return OCEntityHandlerResult::OC_EH_ERROR;
+ switch (type)
+ {
+ case 0:
+ return OCEntityHandlerResult::OC_EH_OK;
+ case 1:
+ return OCEntityHandlerResult::OC_EH_ERROR;
+ case 2:
+ return OCEntityHandlerResult::OC_EH_RESOURCE_CREATED;
+ case 3:
+ return OCEntityHandlerResult::OC_EH_RESOURCE_DELETED;
+ case 4:
+ return OCEntityHandlerResult::OC_EH_SLOW;
+ case 5:
+ return OCEntityHandlerResult::OC_EH_FORBIDDEN;
+ case 6:
+ return OCEntityHandlerResult::OC_EH_RESOURCE_NOT_FOUND;
+ default:
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected OCEntityHandlerResult");
+ return OCEntityHandlerResult::OC_EH_ERROR;
};
}
{
switch (result)
{
- /** Success status code - START HERE.*/
- case OC_STACK_OK:
- return "OK";
- case OC_STACK_RESOURCE_CREATED:
- return "RESOURCE_CREATED";
- case OC_STACK_RESOURCE_DELETED:
- return "RESOURCE_DELETED";
- case OC_STACK_CONTINUE:
- return "CONTINUE";
- /* Error status code - START HERE */
- case OC_STACK_INVALID_URI:
- return "INVALID_URI";
- case OC_STACK_INVALID_QUERY:
- return "INVALID_QUERY";
- case OC_STACK_INVALID_IP:
- return "INVALID_IP";
- case OC_STACK_INVALID_PORT:
- return "INVALID_PORT";
- case OC_STACK_INVALID_CALLBACK:
- return "INVALID_CALLBACK";
- case OC_STACK_INVALID_METHOD:
- return "INVALID_METHOD";
- /** Invalid parameter.*/
- case OC_STACK_INVALID_PARAM:
- return "INVALID_PARAM";
- case OC_STACK_INVALID_OBSERVE_PARAM:
- return "INVALID_OBSERVE_PARAM";
- case OC_STACK_NO_MEMORY:
- return "NO_MEMORY";
- case OC_STACK_COMM_ERROR:
- return "COMM_ERROR";
- case OC_STACK_TIMEOUT:
- return "TIMEOUT";
- case OC_STACK_ADAPTER_NOT_ENABLED:
- return "ADAPTER_NOT_ENABLED";
- case OC_STACK_NOTIMPL:
- return "NOTIMPL";
- /** Resource not found.*/
- case OC_STACK_NO_RESOURCE:
- return "NO_RESOURCE";
- /** e.g: not supported method or interface.*/
- case OC_STACK_RESOURCE_ERROR:
- return "RESOURCE_ERROR";
- case OC_STACK_SLOW_RESOURCE:
- return "SLOW_RESOURCE";
- case OC_STACK_DUPLICATE_REQUEST:
- return "DUPLICATE_REQUEST";
- /** Resource has no registered observers.*/
- case OC_STACK_NO_OBSERVERS:
- return "NO_OBSERVERS";
- case OC_STACK_OBSERVER_NOT_FOUND:
- return "OBSERVER_NOT_FOUND";
- case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
- return "VIRTUAL_DO_NOT_HANDLE";
- case OC_STACK_INVALID_OPTION:
- return "INVALID_OPTION";
- /** The remote reply contained malformed data.*/
- case OC_STACK_MALFORMED_RESPONSE:
- return "MALFORMED_RESPONSE";
- case OC_STACK_PERSISTENT_BUFFER_REQUIRED:
- return "PERSISTENT_BUFFER_REQUIRED";
- case OC_STACK_INVALID_REQUEST_HANDLE:
- return "INVALID_REQUEST_HANDLE";
- case OC_STACK_INVALID_DEVICE_INFO:
- return "INVALID_DEVICE_INFO";
- case OC_STACK_INVALID_JSON:
- return "INVALID_JSON";
- /** Request is not authorized by Resource Server. */
- case OC_STACK_UNAUTHORIZED_REQ:
- return "UNAUTHORIZED_REQ";
- /** Error code from PDM */
- case OC_STACK_PDM_IS_NOT_INITIALIZED:
- return "PDM_IS_NOT_INITIALIZED";
- case OC_STACK_DUPLICATE_UUID:
- return "DUPLICATE_UUID";
- case OC_STACK_INCONSISTENT_DB:
- return "INCONSISTENT_DB";
- /** Error code from OTM */
- case OC_STACK_AUTHENTICATION_FAILURE:
- return "AUTHENTICATION_FAILURE";
- /** Insert all new error codes here!.*/
+ /** Success status code - START HERE.*/
+ case OC_STACK_OK:
+ return "OK";
+ case OC_STACK_RESOURCE_CREATED:
+ return "RESOURCE_CREATED";
+ case OC_STACK_RESOURCE_DELETED:
+ return "RESOURCE_DELETED";
+ case OC_STACK_CONTINUE:
+ return "CONTINUE";
+ /* Error status code - START HERE */
+ case OC_STACK_INVALID_URI:
+ return "INVALID_URI";
+ case OC_STACK_INVALID_QUERY:
+ return "INVALID_QUERY";
+ case OC_STACK_INVALID_IP:
+ return "INVALID_IP";
+ case OC_STACK_INVALID_PORT:
+ return "INVALID_PORT";
+ case OC_STACK_INVALID_CALLBACK:
+ return "INVALID_CALLBACK";
+ case OC_STACK_INVALID_METHOD:
+ return "INVALID_METHOD";
+ /** Invalid parameter.*/
+ case OC_STACK_INVALID_PARAM:
+ return "INVALID_PARAM";
+ case OC_STACK_INVALID_OBSERVE_PARAM:
+ return "INVALID_OBSERVE_PARAM";
+ case OC_STACK_NO_MEMORY:
+ return "NO_MEMORY";
+ case OC_STACK_COMM_ERROR:
+ return "COMM_ERROR";
+ case OC_STACK_TIMEOUT:
+ return "TIMEOUT";
+ case OC_STACK_ADAPTER_NOT_ENABLED:
+ return "ADAPTER_NOT_ENABLED";
+ case OC_STACK_NOTIMPL:
+ return "NOTIMPL";
+ /** Resource not found.*/
+ case OC_STACK_NO_RESOURCE:
+ return "NO_RESOURCE";
+ /** e.g: not supported method or interface.*/
+ case OC_STACK_RESOURCE_ERROR:
+ return "RESOURCE_ERROR";
+ case OC_STACK_SLOW_RESOURCE:
+ return "SLOW_RESOURCE";
+ case OC_STACK_DUPLICATE_REQUEST:
+ return "DUPLICATE_REQUEST";
+ /** Resource has no registered observers.*/
+ case OC_STACK_NO_OBSERVERS:
+ return "NO_OBSERVERS";
+ case OC_STACK_OBSERVER_NOT_FOUND:
+ return "OBSERVER_NOT_FOUND";
+ case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
+ return "VIRTUAL_DO_NOT_HANDLE";
+ case OC_STACK_INVALID_OPTION:
+ return "INVALID_OPTION";
+ /** The remote reply contained malformed data.*/
+ case OC_STACK_MALFORMED_RESPONSE:
+ return "MALFORMED_RESPONSE";
+ case OC_STACK_PERSISTENT_BUFFER_REQUIRED:
+ return "PERSISTENT_BUFFER_REQUIRED";
+ case OC_STACK_INVALID_REQUEST_HANDLE:
+ return "INVALID_REQUEST_HANDLE";
+ case OC_STACK_INVALID_DEVICE_INFO:
+ return "INVALID_DEVICE_INFO";
+ case OC_STACK_INVALID_JSON:
+ return "INVALID_JSON";
+ /** Request is not authorized by Resource Server. */
+ case OC_STACK_UNAUTHORIZED_REQ:
+ return "UNAUTHORIZED_REQ";
+ /** Error code from PDM */
+ case OC_STACK_PDM_IS_NOT_INITIALIZED:
+ return "PDM_IS_NOT_INITIALIZED";
+ case OC_STACK_DUPLICATE_UUID:
+ return "DUPLICATE_UUID";
+ case OC_STACK_INCONSISTENT_DB:
+ return "INCONSISTENT_DB";
+ /** Error code from OTM */
+ case OC_STACK_AUTHENTICATION_FAILURE:
+ return "AUTHENTICATION_FAILURE";
+ /** Insert all new error codes here!.*/
#ifdef WITH_PRESENCE
- case OC_STACK_PRESENCE_STOPPED:
- return "PRESENCE_STOPPED";
- case OC_STACK_PRESENCE_TIMEOUT:
- return "PRESENCE_TIMEOUT";
- case OC_STACK_PRESENCE_DO_NOT_HANDLE:
- return "PRESENCE_DO_NOT_HANDLE";
+ case OC_STACK_PRESENCE_STOPPED:
+ return "PRESENCE_STOPPED";
+ case OC_STACK_PRESENCE_TIMEOUT:
+ return "PRESENCE_TIMEOUT";
+ case OC_STACK_PRESENCE_DO_NOT_HANDLE:
+ return "PRESENCE_DO_NOT_HANDLE";
#endif
- case OC_STACK_ERROR:
- return "ERROR";
+ case OC_STACK_ERROR:
+ return "ERROR";
- case JNI_EXCEPTION:
- return "JNI_EXCEPTION";
- case JNI_NO_NATIVE_POINTER:
- return "JNI_NO_NATIVE_POINTER";
- case JNI_INVALID_VALUE:
- return "JNI_INVALID_VALUE";
- default:
- return "";
+ case JNI_EXCEPTION:
+ return "JNI_EXCEPTION";
+ case JNI_NO_NATIVE_POINTER:
+ return "JNI_NO_NATIVE_POINTER";
+ case JNI_INVALID_VALUE:
+ return "JNI_INVALID_VALUE";
+ default:
+ return "";
}
}
};
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base;
+
+import java.util.List;
+import java.util.EnumSet;
+import java.util.Map;
+import java.util.Arrays;
+import java.util.ArrayList;
+
+public class OcDirectPairDevice {
+
+
+ private long mNativeHandle;
+ private String mdeviceID;
+ private String mHost;
+
+ private OcDirectPairDevice(long nativeHandle) {
+ this.mNativeHandle = nativeHandle;
+ }
+
+ public OcDirectPairDevice(String deviceID)
+ {
+ this.mdeviceID = deviceID;
+ }
+
+ public String getDevId()
+ {
+ return this.mdeviceID;
+ }
+
+ public native String getHost();
+
+ public List<Integer> getPairingMethodList() {
+ int [] intList = this.getPairingMethods();
+ List<Integer> prmList = new ArrayList<Integer>();
+ for (int i = 0; i < intList.length; i++)
+ {
+ prmList.add(intList[i]);
+ }
+ return prmList;
+ }
+
+ private native int[] getPairingMethods();
+
+ /**
+ * Method to get the connectivity type of this resource
+ *
+ * @return EnumSet<OcConnectivityType></OcConnectivityType> connectivity type set
+ */
+ public EnumSet<OcConnectivityType> getConnectivityTypeSet() {
+ return OcConnectivityType.convertToEnumSet(
+ this.getConnectivityTypeN()
+ );
+ }
+
+ private native int getConnectivityTypeN();
+
+
+ /**
+ * Method to get list of all paired devices for a given device.
+ *
+ * @param GetDirectPairedListener Callback function, which will receive the list of direct paired devices.
+ * @throws OcException
+ */
+
+ public native void getDirectPairedDevices(GetDirectPairedListener getDirectPairedListener) throws OcException;
+
+ public interface GetDirectPairedListener {
+ public void getDirectPairedListener(List<String> ocPairedDeviceList);
+ }
+
+ /**
+ * Method to perform direct pairing between two devices.
+ *
+ * @param DirectPairingListener Callback function, which will be called after
+ * completion of direct pairing.
+ * @throws OcException
+ */
+ public native void doDirectPairing(OcDirectPairDevice peer,
+ OcPrmType pmSel, String pinNumber,
+ DirectPairingListener directPairingListener) throws OcException;
+
+
+ public interface DirectPairingListener {
+ public void directPairingListener(String devId, int result);
+ }
+
+ @Override
+ public String toString() {
+ return this.mdeviceID;
+ }
+}
throws OcException;
/**
+ * Method to find all devices which are eligible for direct pairing and return the list.
+ *
+ * @param timeout timeout for discovering direct pair devices.
+ * @param FindDirectPairingListener Callback function, which will receive the list of direct
+ * pairable devices.
+ * @throws OcException
+ */
+ public static native void findDirectPairingDevices(int timeout,
+ FindDirectPairingListener onFindDirectPairingListener) throws OcException;
+
+ /**
+ * Method to get list of all paired devices for a given device.
+ *
+ * @param GetDirectPairedListener Callback function, which will receive the list of direct
+ * paired devices.
+ * @throws OcException
+ */
+ public native void getDirectPairedDevices(GetDirectPairedListener onGetDirectPairedListener)
+ throws OcException;
+
+ /**
+ * Method to perform direct pairing between two devices.
+ *
+ * @param peer Target peer
+ * @param prmType Pairing Method to be used for Pairing
+ * @param pin pin
+ * @param DirectPairingListener Callback function, which will be called after
+ * completion of direct pairing.
+ * @throws OcException
+ */
+ public static void doDirectPairing(
+ OcDirectPairDevice peer,
+ OcPrmType prmType,
+ String pin,
+ DirectPairingListener onDirectPairingListener) throws OcException {
+
+ OcPlatform.doDirectPairing0(
+ peer,
+ prmType.getValue(),
+ pin,
+ onDirectPairingListener
+ );
+ }
+
+ private static native void doDirectPairing0(OcDirectPairDevice peer,
+ int pmSel, String pinNumber, DirectPairingListener onDirectPairingListener)
+ throws OcException;
+
+ /**
+ * An FindDirectPairingListener can be registered via the OcPlatform.findDirectPairingDevices call.
+ * Event listeners are notified asynchronously
+ */
+ public interface FindDirectPairingListener {
+ public void onFindDirectPairingListener(List<OcDirectPairDevice> ocPairedDeviceList);
+ }
+
+ /**
+ * Listerner to Get List of already Direct Paired devices.
+ * An GetDirectPairedListener can be registered via the OcPlatform.getDirectPairedDevices call.
+ * Event listeners are notified asynchronously
+ */
+ public interface GetDirectPairedListener {
+ public void onGetDirectPairedListener(List<OcDirectPairDevice> ocPairedDeviceList);
+ }
+
+ /**
+ * Listner to get result of doDirectPairing.
+ * An DirectPairingListener can be registered via the OcPlatform.doDirectPairing call.
+ * Event listeners are notified asynchronously
+ */
+ public interface DirectPairingListener {
+ public void onDirectPairingListener(String devId, int result);
+ }
+
+ /**
* An OnResourceFoundListener can be registered via the OcPlatform.findResource call.
* Event listeners are notified asynchronously
*/
--- /dev/null
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ * //\r
+ * // Licensed under the Apache License, Version 2.0 (the "License");\r
+ * // you may not use this file except in compliance with the License.\r
+ * // You may obtain a copy of the License at\r
+ * //\r
+ * // http://www.apache.org/licenses/LICENSE-2.0\r
+ * //\r
+ * // Unless required by applicable law or agreed to in writing, software\r
+ * // distributed under the License is distributed on an "AS IS" BASIS,\r
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * // See the License for the specific language governing permissions and\r
+ * // limitations under the License.\r
+ * //\r
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+/**\r
+ * @brief direct pairing Method Type.\r
+ * 0: not allowed\r
+ * 1: pre-configured pin\r
+ * 2: random pin\r
+ */\r
+package org.iotivity.base;\r
+\r
+public enum OcPrmType {\r
+ DP_INVALID (-1),\r
+ DP_NOT_ALLOWED (0),\r
+ DP_PRE_CONFIGURED (1 << 0),\r
+ DP_RANDOM_PIN (1 << 1);\r
+\r
+ private int value;\r
+\r
+ private OcPrmType(int value) {\r
+ this.value = value;\r
+ }\r
+\r
+ public int getValue() {\r
+ return this.value;\r
+ }\r
+\r
+ public static OcPrmType convertOcPrmType(int value) {\r
+ switch (value)\r
+ {\r
+ case 0:\r
+ return OcPrmType.DP_NOT_ALLOWED;\r
+ case 1:\r
+ return OcPrmType.DP_PRE_CONFIGURED;\r
+ case 2:\r
+ return OcPrmType.DP_RANDOM_PIN;\r
+ }\r
+ return OcPrmType.DP_INVALID;\r
+ }\r
+}\r
ProvisionPairwiseDevicesListener provisionPairwiseDevicesListener) throws OcException;
/**
+ * Method to configure resource for direct pairing
+ *
+ * @param pin pin number
+ * @param pdacls Array of Device Pairing Access Control List
+ * @param type List of supported OcPrmType
+ * @param edp enable (1) / disable (0)
+ * @param ProvisionDirectPairing Callback function, which will be called after completion
+ * of Direct Pairing.
+ * @throws OcException
+ */
+
+ public void doProvisionDirectPairing(String pin, OicSecPdAcl[] pdacls, List<OcPrmType> type,
+ boolean edp , ProvisionDirectPairingListener provisionDirectPairingListener)
+ throws OcException {
+
+ int[] typeArray = new int[type.size()];
+ int i = 0;
+ for (OcPrmType ocPrmType:type) {
+ typeArray[i++] = ocPrmType.getValue();
+ }
+
+ this.provisionDirectPairing(pin, pdacls, typeArray, (edp?1:0),
+ provisionDirectPairingListener);
+ }
+
+ private native void provisionDirectPairing(String pin, OicSecPdAcl[] pdacls, int[] type,
+ int edp , ProvisionDirectPairingListener provisionDirectPairingListener)
+ throws OcException;
+
+ /**
+ * provisionDirectPairingListener can be registered with doOwnershipTransfer
+ * call.
+ * Listener notified asynchronously.
+ */
+ public interface ProvisionDirectPairingListener {
+ public void provisionDirectPairingListener(List<ProvisionResult> provisionResultList,
+ int hasError);
+ }
+
+ /**
* doOwnershipTransferListener can be registered with doOwnershipTransfer
* call.
* Listener notified asynchronously.
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Arrays;
+
+public class OicSecPdAcl implements Serializable {
+
+ private int mPermission;
+ private List<String> mResources;
+ private List<String> mPeriods;
+ private List<String> mRecurrences;
+
+ public OicSecPdAcl(List<String> recurrences, List<String> periods, int permission,
+ List<String> resources) {
+ this.mRecurrences = recurrences;
+ this.mPeriods = periods;
+ this.mPermission = permission;
+ this.mResources = resources;
+ }
+
+ public List<String> getRecurrences() {
+ return mRecurrences;
+ }
+
+ public void setRecurrences(List<String> recurrences) {
+ this.mRecurrences = recurrences;
+ }
+
+ public List<String> getPeriods() {
+ return mPeriods;
+ }
+
+ public void setPeriods(List<String> periods) {
+ this.mPeriods = periods;
+ }
+
+ public int getPermission() {
+ return this.mPermission;
+ }
+
+ public void setPermission(int permission) {
+ this.mPermission = permission;
+ }
+
+ public List<String> getResources() {
+ return mResources;
+ }
+
+ public void setResources(List<String> resources) {
+ this.mResources = resources;
+ }
+
+ public int getResourcesCount() {
+ return this.mResources.size();
+ }
+
+ public String getResources(int i) {
+ return this.mResources.get(i);
+ }
+
+ public int getPeriodsCount() {
+ return this.mPeriods.size();
+ }
+
+ public String getPeriods(int i) {
+ return this.mPeriods.get(i);
+ }
+
+ public String getRecurrences(int i) {
+ return this.mRecurrences.get(i);
+ }
+}
private static Context mContext;
private CaBtPairingInterface(Context context) {
- mContext = context;
+ synchronized(CaBtPairingInterface.class) {
+ mContext = context;
+ }
registerIntentFilter();
}
private static Context mContext;
private CaEdrInterface(Context context) {
- mContext = context;
+ synchronized(CaEdrInterface.class) {
+ mContext = context;
+ }
registerIntentFilter();
}
}\r
\r
private CaIpInterface(Context context) {\r
- mContext = context;\r
+ synchronized(CaIpInterface.class) {\r
+ mContext = context;\r
+ }\r
registerIpStateReceiver();\r
}\r
\r
private CaLeClientInterface(Context context) {
caLeRegisterLeScanCallback(mLeScanCallback);
caLeRegisterGattCallback(mGattCallback);
- mContext = context;
+ synchronized(CaLeClientInterface.class) {
+ mContext = context;
+ }
registerIntentFilter();
}
+
+
public static void getLeScanCallback() {
caLeRegisterLeScanCallback(mLeScanCallback);
}
private CaNfcInterface(Context context, Activity activity) {
Log.d(MYTAG, "NFC registerNfcReceiver");
- mContext = context;
+ synchronized(CaNfcInterface.class) {
+ mContext = context;
+ }
mActivity = activity;
mAdapter = NfcAdapter.getDefaultAdapter(mContext);
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>\r
+<classpath>\r
+ <classpathentry kind="src" path="src"/>\r
+ <classpathentry kind="src" path="gen"/>\r
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>\r
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>\r
+ <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>\r
+ <classpathentry kind="output" path="bin/classes"/>\r
+</classpath>\r
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>\r
+<projectDescription>\r
+ <name>Iot</name>\r
+ <comment></comment>\r
+ <projects>\r
+ </projects>\r
+ <buildSpec>\r
+ <buildCommand>\r
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>\r
+ <arguments>\r
+ </arguments>\r
+ </buildCommand>\r
+ <buildCommand>\r
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>\r
+ <arguments>\r
+ </arguments>\r
+ </buildCommand>\r
+ <buildCommand>\r
+ <name>org.eclipse.jdt.core.javabuilder</name>\r
+ <arguments>\r
+ </arguments>\r
+ </buildCommand>\r
+ <buildCommand>\r
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>\r
+ <arguments>\r
+ </arguments>\r
+ </buildCommand>\r
+ </buildSpec>\r
+ <natures>\r
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>\r
+ <nature>org.eclipse.jdt.core.javanature</nature>\r
+ </natures>\r
+</projectDescription>\r
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":DirectPairing" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+ <component name="FacetManager">
+ <facet type="android-gradle" name="Android-Gradle">
+ <configuration>
+ <option name="GRADLE_PROJECT_PATH" value=":DirectPairing" />
+ </configuration>
+ </facet>
+ <facet type="android" name="Android">
+ <configuration>
+ <option name="SELECTED_BUILD_VARIANT" value="debug" />
+ <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+ <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+ <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+ <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
+ <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
+ <afterSyncTasks>
+ <task>generateDebugAndroidTestSources</task>
+ <task>generateDebugSources</task>
+ </afterSyncTasks>
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />
+ <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+ <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+ <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
+ <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+ </configuration>
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
+ <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+ <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+ <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/reports" />
+ <excludeFolder url="file://$MODULE_DIR$/build/test-results" />
+ <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+ </content>
+ <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-" level="project" />
+ <orderEntry type="library" exported="" name="android-android-21" level="project" />
+ </component>
+</module>
--- /dev/null
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion "20.0.0"\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.base.examples.DirectPairing"\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ versionCode 1\r
+ versionName "1.0"\r
+ }\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+ }\r
+ }\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+}\r
+repositories {\r
+ flatDir {\r
+ dirs "../../android_api/base/build/outputs/aar/"\r
+ }\r
+}\r
+\r
+try {\r
+ dependencies {\r
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+ }\r
+} catch (all) {\r
+ print "${ERROR_MSG}"\r
+ assert all\r
+}\r
+\r
--- /dev/null
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-23
+android.library.reference.1=../appcompat_v7
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="org.iotivity.base.examples.DirectPairing"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk
+ android:minSdkVersion="19"
+ android:targetSdkVersion="21" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ <activity
+ android:name=".MainActivity"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples.DirectPairing;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.BaseExpandableListAdapter;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import org.iotivity.base.examples.DirectPairing.Led;
+
+import java.util.List;
+
+public class ExpandableListAdapter extends BaseExpandableListAdapter {
+ private List<String> mGroupList;
+ private List<Object> mChilditemsList;
+ private Context mContext;
+
+ public ExpandableListAdapter(List<String> groupList, List<Object> childitemsList,
+ Context context) {
+ super();
+ this.mContext = context;
+ this.mGroupList = groupList;
+ this.mChilditemsList = childitemsList;
+ }
+
+ @Override
+ public int getGroupCount() {
+ return mGroupList.size();
+ }
+
+ @Override
+ public int getChildrenCount(int groupPosition) {
+ return 1;
+ }
+
+ @Override
+ public Object getGroup(int groupPosition) {
+ return mGroupList.get(groupPosition);
+ }
+
+ @Override
+ public Object getChild(int groupPosition, int childPosition) {
+ return this.mChilditemsList.get(childPosition);
+ }
+
+ @Override
+ public long getGroupId(int groupPosition) {
+ return groupPosition;
+ }
+
+ @Override
+ public long getChildId(int groupPosition, int childPosition) {
+ return childPosition;
+ }
+
+ @Override
+ public boolean hasStableIds() {
+ return false;
+ }
+
+ @Override
+ public View getGroupView(int groupPosition, boolean isExpanded,
+ View convertView, ViewGroup parent) {
+
+ String data = (String) getGroup(groupPosition);
+ if (convertView == null) {
+ LayoutInflater infalInflater = (LayoutInflater) this.mContext
+ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ convertView = infalInflater.inflate(R.layout.list_group, null);
+ }
+
+ ImageView img = (ImageView) convertView.findViewById(R.id.image);
+ if (isExpanded) {
+ img.setImageResource(R.drawable.arrow_down);
+
+ } else {
+ img.setImageResource(R.drawable.arrow_right);
+ }
+
+ TextView groupText = (TextView) convertView.findViewById(R.id.title);
+ groupText.setText(mGroupList.get(groupPosition));
+
+ return convertView;
+ }
+
+ @Override
+ public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
+ View convertView, ViewGroup parent) {
+ LayoutInflater inflater = (LayoutInflater) mContext
+ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ convertView = inflater.inflate(R.layout.list_item, parent, false);
+
+ Led ledResource = (Led) getChild(groupPosition, childPosition);
+ TextView textItem = (TextView) convertView
+ .findViewById(R.id.textViewItem);
+ TextView textSource = (TextView) convertView
+ .findViewById(R.id.textViewSource);
+ TextView textStatus = (TextView) convertView
+ .findViewById(R.id.textViewStatus);
+ textStatus.setText("URI:" + "/a/led");
+ textItem.setText("State: " + ledResource.getState());
+ textSource.setText("Power: " + ledResource.getPower());
+
+ return convertView;
+
+ }
+
+ @Override
+ public boolean isChildSelectable(int groupPosition, int childPosition) {
+ return true;
+ }
+
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples.DirectPairing;
+
+/**
+ * Led
+ * <p/>
+ * This class is used by simpleclient to create an object and update the values depending
+ * on the server response
+ */
+public class Led {
+ private boolean mState;
+ private int mPower;
+ private String mUri;
+
+ // constructor
+ public Led() {
+ mState = false;
+ mPower = 0;
+ mUri = "";
+ }
+
+ // accessor methods
+ public boolean getState() {
+ return mState;
+ }
+
+ public void setState(boolean state) {
+ mState = state;
+ }
+
+ public int getPower() {
+ return mPower;
+ }
+
+ public void setPower(int power) {
+ mPower = power;
+ }
+
+ public String getUri() {
+ return mUri;
+ }
+
+ public void setUri(String uri) {
+ mUri = uri;
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples.DirectPairing;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.ProgressDialog;
+import android.content.DialogInterface;
+import android.content.SharedPreferences;
+import android.graphics.Color;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.Environment;
+import android.preference.PreferenceManager;
+import android.text.InputFilter;
+import android.util.Log;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.ExpandableListView;
+import android.widget.ExpandableListView.OnGroupExpandListener;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.Switch;
+import android.widget.Toast;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcDirectPairDevice;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcPrmType;
+import org.iotivity.base.OcProvisioning;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+import org.iotivity.base.examples.DirectPairing.Led;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.channels.FileChannel;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+public class MainActivity extends Activity {
+ private static final int BUFFER_SIZE = 1024;
+ private static final String TAG = "DirectPairing: ";
+ private static int selected = -1;
+ private int[] pList;
+ private Button save;
+ private int prmType;
+ private EditText pinText;
+ private Led ledResource;
+ private ListView mListView;
+ private String filePath = "";
+ private OcResource led = null;
+ private Switch discoverButton;
+ private List<String> resourceInterfaces;
+ private ArrayAdapter<String> arrayAdapter;
+ private List<Object> onGetResponseList;
+ private ExpandableListAdapter exlistAdapter;
+ OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ onGetResponseList = new ArrayList<Object>();
+ ledResource.setState(ocRepresentation.getValueBool("state"));
+ ledResource.setPower(ocRepresentation.getValueInt("power"));
+ ledResource.setUri(ocRepresentation.getUri());
+ runOnUiThread(new Runnable() {
+ public void run() {
+ onGetResponseList.add(ledResource);
+ exlistAdapter.notifyDataSetChanged();
+ }
+ });
+
+ Log.d(TAG, "Got a response from " + ocRepresentation.getUri() +
+ " " + ocRepresentation.getValueBool("state") + " "
+ + ocRepresentation.getValueInt("power") + " " +
+ ocRepresentation.getValueString("name"));
+ }
+
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ Log.d(TAG, "GET request has failed");
+ Log.e(TAG, throwable.toString());
+ }
+ };
+ private ExpandableListView mPairedListDisplay;
+ private ArrayAdapter<OcDirectPairDevice> adapter;
+ private List<String> pairedList;
+ private List<OcDirectPairDevice> discoveredListObj;
+ OcPlatform.DirectPairingListener doDPListener = new OcPlatform.DirectPairingListener() {
+ @Override
+ public void onDirectPairingListener(String devId, int result) {
+ Log.d(TAG, "Inside getDPListener");
+ if (result == StringConstants.SUCCES_CODE) {
+ pairedList.clear();
+ pairedList.add(devId);
+ onGetResponseList.add(new Led());
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mPairedListDisplay.setAdapter(exlistAdapter);
+ int pos = mListView.getCheckedItemPosition();
+ if (pos != ListView.INVALID_POSITION && discoveredListObj.size() != 0) {
+ discoveredListObj.remove(pos);
+ adapter.notifyDataSetChanged();
+ }
+ }
+ });
+ Log.d(TAG, "direct pair successfull for " + devId);
+ } else {
+ Log.d(TAG, "direct pairing failed");
+ runOnUiThread(new Runnable() {
+ public void run() {
+ Toast.makeText(getApplicationContext(),
+ "Direct Pairing Failed", Toast.LENGTH_SHORT).show();
+ }
+ });
+ }
+ exportCBOR();
+ }
+ };
+ private List<OcDirectPairDevice> discoveredPairableDevices;
+ OcPlatform.FindDirectPairingListener finddirectPairing =
+ new OcPlatform.FindDirectPairingListener() {
+ @Override
+ public void onFindDirectPairingListener(List<OcDirectPairDevice> direcPairingDevice) {
+ Log.d(TAG, "find direct pairable successfull ");
+ discoveredListObj.clear();
+ discoveredPairableDevices =
+ new ArrayList<OcDirectPairDevice>(direcPairingDevice);
+ for (int i = 0; i < direcPairingDevice.size(); i++) {
+ OcDirectPairDevice dpPairDevice = direcPairingDevice.get(i);
+ Log.d(TAG, "getHost from Find Direct Pairing " + dpPairDevice.getHost());
+ discoveredListObj.add(dpPairDevice);
+ }
+
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
+ mListView.setAdapter(adapter);
+ discoverButton.setChecked(false);
+ }
+ });
+ }
+ };
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+
+ onGetResponseList = new ArrayList<Object>();
+ discoveredListObj = new ArrayList<OcDirectPairDevice>();
+ pairedList = new ArrayList<String>();
+
+ ledResource = new Led();
+
+ mListView = (ListView) findViewById(R.id.list_view);
+ discoverButton = (Switch) findViewById(R.id.discover);
+ mPairedListDisplay = (ExpandableListView) findViewById(R.id.list_view_paired_list);
+
+
+ filePath = getFilesDir().getPath() + "/"; // data/data/<package>/files/
+ //copy CBOR file when application runs first time
+ SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
+ boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
+ if (isFirstRun) {
+ copyCborFromAsset();
+ SharedPreferences.Editor editor = wmbPreference.edit();
+ editor.putBoolean("FIRSTRUN", false);
+ editor.commit();
+ }
+
+ initOICStack();
+
+ adapter = new ArrayAdapter<OcDirectPairDevice>(this,
+ android.R.layout.simple_list_item_single_choice,
+ discoveredListObj);
+
+ arrayAdapter = new ArrayAdapter<String>(
+ MainActivity.this,
+ android.R.layout.select_dialog_singlechoice);
+
+ save = (Button) findViewById(R.id.saveDiscovered);
+
+ save.setEnabled(false);
+ save.setBackgroundColor(Color.GRAY);
+
+ resourceInterfaces = new LinkedList<>();
+ resourceInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
+
+ exlistAdapter = new ExpandableListAdapter(pairedList, onGetResponseList,
+ MainActivity.this);
+ mPairedListDisplay.setAdapter(exlistAdapter);
+
+ // to expand only a single group item.
+ mPairedListDisplay.setOnGroupExpandListener(new OnGroupExpandListener() {
+ int previousGroup = -1;
+
+ @Override
+ public void onGroupExpand(int groupPosition) {
+ Log.d(TAG, "Calling GET api on mResource");
+ try {
+ if (null != led) led.get(new HashMap<String, String>(), onGetListener);
+ } catch (OcException e) {
+ Log.d(TAG, "Error in GET calls");
+ Log.e(TAG, e.getMessage());
+ }
+
+ if (groupPosition != previousGroup)
+ mPairedListDisplay.collapseGroup(previousGroup);
+
+ previousGroup = groupPosition;
+ }
+ });
+
+ save.setOnClickListener(new View.OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+
+ AlertDialog.Builder alertPinDialog =
+ new AlertDialog.Builder(MainActivity.this);
+ alertPinDialog.setTitle("PIN");
+ alertPinDialog.setMessage("Enter Pin");
+
+ pinText = new EditText(MainActivity.this);
+ int maxLength = 8;
+ InputFilter[] fArray = new InputFilter[1];
+ fArray[0] = new InputFilter.LengthFilter(maxLength);
+ pinText.setFilters(fArray);
+ pinText.setMaxLines(1);
+ LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.MATCH_PARENT);
+ pinText.setLayoutParams(lp);
+ alertPinDialog.setView(pinText);
+ alertPinDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ selected = -1;
+ final AlertDialog alertPrmTypeDialog = new AlertDialog.Builder
+ (MainActivity.this)
+ .setSingleChoiceItems(arrayAdapter, -1,
+ new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ selected = which;
+ prmType = pList[which];
+ Log.d(TAG, " prmType " + prmType);
+ }
+ })
+ .setTitle("Select Direct Pair Method")
+ .setPositiveButton("OK", null)
+ .setNegativeButton("CANCEL", null)
+ .create();
+
+ alertPrmTypeDialog.setOnShowListener(
+ new DialogInterface.OnShowListener() {
+ @Override
+ public void onShow(DialogInterface dialog) {
+ Button ok =
+ alertPrmTypeDialog
+ .getButton(AlertDialog.BUTTON_POSITIVE);
+
+ Button cancel =
+ alertPrmTypeDialog
+ .getButton(AlertDialog.BUTTON_NEGATIVE);
+
+ ok.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ int pos = mListView.getCheckedItemPosition();
+ if (selected == -1) {
+ Toast.makeText(getApplicationContext(),
+ "Please Select A Value",
+ Toast.LENGTH_SHORT).show();
+ } else if (pos != ListView.INVALID_POSITION) {
+ if (!discoveredListObj.isEmpty()) {
+ try {
+ OcDirectPairDevice peer =
+ (OcDirectPairDevice)
+ discoveredListObj.
+ get(pos);
+ OcPlatform.doDirectPairing(peer,
+ OcPrmType.convertOcPrmType(prmType),
+ pinText.getText().toString(),
+ doDPListener);
+ } catch (OcException e) {
+ Log.d(TAG, "do Direct Pairing error: "
+ + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+
+ alertPrmTypeDialog.dismiss();
+ } else {
+ alertPrmTypeDialog.dismiss();
+ }
+ }
+ }
+ });
+
+ cancel.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ alertPrmTypeDialog.dismiss();
+ }
+ });
+ }
+ });
+
+ alertPrmTypeDialog.show();
+ }
+ });
+ alertPinDialog.show();
+ }
+ });
+
+ mListView.setOnItemClickListener(new OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView adapt, View view, int position, long itemId) {
+ save.setEnabled(true);
+ save.setBackgroundColor(Color.parseColor("#13AEF4"));
+ OcDirectPairDevice dpPairDevice =
+ (OcDirectPairDevice) adapt.getItemAtPosition(position);
+ Log.d(TAG, "DevId On List Item Clicked " + dpPairDevice.getDevId());
+ List<Integer> pTypeList = dpPairDevice.getPairingMethodList();
+ pList = new int[pTypeList.size()];
+ Iterator<Integer> iterator = pTypeList.iterator();
+ for(int k = 0; k < pList.length; k++){
+ pList[k]=iterator.next().intValue();
+ }
+ arrayAdapter.clear();
+ for (int j = 0; j < pList.length; j++) {
+ Log.d(TAG, " List Item Value " + pList[j]);
+ OcPrmType prmTy = OcPrmType.convertOcPrmType(pList[j]);
+ arrayAdapter.add(prmTy.name());
+ }
+ }
+ });
+
+ discoverButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (isChecked) {
+ save.setEnabled(false);
+ save.setBackgroundColor(Color.GRAY);
+ new GetDiscoveredItems().execute();
+ }
+ }
+ });
+
+ }
+
+ /**
+ * Copy svr db CBOR dat file from assets folder to app data files dir
+ */
+ private void copyCborFromAsset() {
+ InputStream inputStream = null;
+ OutputStream outputStream = null;
+ int length;
+ byte[] buffer = new byte[BUFFER_SIZE];
+ try {
+ inputStream = getAssets().open(StringConstants.OIC_CLIENT_CBOR_DB_FILE);
+ File file = new File(filePath);
+ //check files directory exists
+ if (!(file.exists() && file.isDirectory())) {
+ file.mkdirs();
+ }
+ outputStream = new FileOutputStream(filePath +
+ StringConstants.OIC_CLIENT_CBOR_DB_FILE);
+ while ((length = inputStream.read(buffer)) != -1) {
+ outputStream.write(buffer, 0, length);
+ }
+ } catch (NullPointerException e) {
+ Log.d(TAG, "Null pointer exception " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ } catch (FileNotFoundException e) {
+ Log.d(TAG, "CBOR svr db file not found " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ } catch (IOException e) {
+ Log.d(TAG, StringConstants.OIC_CLIENT_CBOR_DB_FILE + " file copy failed");
+ Log.e(TAG, e.getMessage());
+ } finally {
+ if (inputStream != null) {
+ try {
+ inputStream.close();
+ } catch (IOException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ if (outputStream != null) {
+ try {
+ outputStream.close();
+ } catch (IOException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ }
+ }
+
+ void exportCBOR() {
+ try {
+ File sd = Environment.getExternalStorageDirectory();
+ File data = Environment.getDataDirectory();
+ if (sd.canWrite()) {
+ String currentDBPath = "/data/data/" + getPackageName() +
+ "/files/" + StringConstants.OIC_CLIENT_CBOR_DB_FILE;
+ File currentDB = new File(currentDBPath);
+ File backupDB = new File(sd, StringConstants.OIC_CLIENT_CBOR_DB_FILE);
+ if (currentDB.exists()) {
+ FileChannel src = new FileInputStream(currentDB).getChannel();
+ FileChannel dst = new FileOutputStream(backupDB).getChannel();
+ dst.transferFrom(src, 0, src.size());
+ src.close();
+ dst.close();
+ }
+ }
+ } catch (Exception e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * configure OIC platform and call findResource
+ */
+ private void initOICStack() {
+ //create platform config
+ PlatformConfig cfg = new PlatformConfig(this, ServiceType.IN_PROC, ModeType.CLIENT_SERVER,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
+ OcPlatform.Configure(cfg);
+ try {
+ /*
+ * Initialize DataBase
+ */
+ String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
+ File.separator;
+ File file = new File(sqlDbPath);
+ //check files directory exists
+ if (!(file.isDirectory())) {
+ file.mkdirs();
+ Log.d(TAG, "Sql db directory created at " + sqlDbPath);
+ }
+ Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
+ OcProvisioning.provisionInit(sqlDbPath + StringConstants.OIC_SQL_DB_FILE);
+ } catch (OcException e) {
+ Log.d(TAG, "provisionInit error: " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ class GetDiscoveredItems extends AsyncTask<Void, Void, List<String>> {
+
+ ProgressDialog pDialog;
+
+ @Override
+ protected void onPreExecute() {
+ pDialog = new ProgressDialog(MainActivity.this);
+ pDialog.setMessage("Getting Discovered Items");
+ pDialog.setCancelable(false);
+ pDialog.setCanceledOnTouchOutside(false);
+ pDialog.show();
+ }
+
+ ;
+
+ @Override
+ protected List<String> doInBackground(Void... params) {
+ try {
+ OcPlatform.findDirectPairingDevices(5, finddirectPairing);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(List<String> discoveredItems) {
+ pDialog.dismiss();
+ for (Iterator iterator = discoveredListObj.iterator(); iterator.hasNext(); ) {
+ OcDirectPairDevice ledResource = (OcDirectPairDevice) iterator.next();
+ List<String> lightTypes = new LinkedList<>();
+ lightTypes.add("core.led");
+ try {
+ Log.d(TAG, "Constructing Led Resource");
+ led = OcPlatform.constructResourceObject(ledResource.getHost(),
+ "/a/led", ledResource.getConnectivityTypeSet(),
+ false, //isObservable
+ lightTypes,
+ resourceInterfaces);
+ Log.d(TAG, "Constructed Led Resource");
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ }
+
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples.DirectPairing;
+
+public interface StringConstants {
+
+ public static final int NUMBER_ZERO = 0;
+ public static final int DISCOVERY_TIMEOUT_10 = 10;
+ public static final int DISCOVERY_TIMEOUT_20 = 20;
+ public static final int SUCCES_CODE = 0;
+ public static final String DEFAULT_ROWNER_ID = "61646d69-6e44-6576-6963-655555494430";
+ public static final String DEFAULT_RESOURCES = "*";
+ public static final String DEFAULT_RECURRENCES = "Daily";
+ public static final String DEFAULT_PERIOD = "12-12-16";
+ public static final int DEFAULT_PERMISSION = 31;
+ public static final String OIC_CLIENT_CBOR_DB_FILE = "oic_svr_db_client_directpairing.dat";
+ public static final String MESSAGE = "message";
+ public static final String OIC_SQL_DB_FILE = "Pdm.db";
+ public static final int CREDENTIAL_TYPE = 1;
+ public static final int OWNER_PSK_LENGTH_128 = 128 / 8;
+}
--- /dev/null
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+ xmlns:tools="http://schemas.android.com/tools"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="match_parent"\r
+ android:orientation="vertical"\r
+ android:paddingBottom="@dimen/activity_vertical_margin"\r
+ android:paddingLeft="@dimen/activity_horizontal_margin"\r
+ android:paddingRight="@dimen/activity_horizontal_margin"\r
+ android:paddingTop="@dimen/activity_vertical_margin"\r
+ tools:context="com.example.iot.MainActivity" >\r
+\r
+ <LinearLayout\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:weightSum="1" >\r
+\r
+ <TextView\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:layout_weight="0.75"\r
+ android:gravity="center"\r
+ android:text="@string/discover_items"\r
+ android:textSize="18sp" />\r
+\r
+ <Switch\r
+ android:id="@+id/discover"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:layout_weight="0.25" />\r
+ </LinearLayout>\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+ <ListView\r
+ android:id="@+id/list_view"\r
+ android:layout_width="match_parent"\r
+ android:layout_height="250dp" />\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+ <RelativeLayout\r
+ android:id="@+id/relLay"\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="wrap_content"\r
+ android:orientation="horizontal"\r
+ android:padding="15dp" >\r
+\r
+ <Button\r
+ android:id="@+id/saveDiscovered"\r
+ android:layout_width="90dp"\r
+ android:layout_height="30dp"\r
+ android:layout_centerInParent="true"\r
+ android:background="#13AEF4"\r
+ android:text="Save"\r
+ android:textColor="#FFFFFF" />\r
+ </RelativeLayout>\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+ <TextView\r
+ android:layout_width="match_parent"\r
+ android:layout_height="wrap_content"\r
+ android:layout_gravity="center_vertical"\r
+ android:paddingLeft="50dp"\r
+ android:text="@string/paired_list"\r
+ android:textSize="18sp" />\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+ <ExpandableListView\r
+ android:id="@+id/list_view_paired_list"\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="200dp"\r
+ android:paddingTop="5dp"\r
+ android:groupIndicator="@null" >\r
+ </ExpandableListView>\r
+\r
+ <View\r
+ android:layout_width="match_parent"\r
+ android:layout_height="2dp"\r
+ android:background="#13AEF4" />\r
+\r
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:padding="10dp" >
+
+ <TextView
+ android:id="@+id/textView"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Discovered Items"
+ android:layout_centerVertical="true"
+ android:layout_gravity="center_vertical"
+ android:textColor="#545454"
+ android:textSize="15sp" />
+
+ <LinearLayout
+ android:id="@+id/linearLay"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentRight="true"
+ android:layout_centerVertical="true" >
+
+ <CheckBox
+ android:id="@+id/checkBox"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerVertical="true"
+ android:layout_gravity="center_vertical"
+ android:layout_marginRight="10dp" />
+ </LinearLayout>
+
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<selector xmlns:android="http://schemas.android.com/apk/res/android">\r
+Â <item android:drawable="@drawable/arrow_right" android:state_empty="true"></item>\r
+Â Â Â Â <item android:drawable="@drawable/arrow_down" android:state_expanded="true"></item>\r
+Â Â Â Â <item android:drawable="@drawable/arrow_right"></item>\r
+\r
+</selector>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>\r
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="40dp"\r
+ android:background="#ffffff"\r
+ android:orientation="horizontal" >\r
+\r
+ <TextView\r
+ android:id="@+id/title"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="40dp"\r
+ android:layout_weight="0.9"\r
+ android:gravity="center_vertical"\r
+ android:paddingLeft="40dp"\r
+ android:text="Items"\r
+ android:textColor="#040404"\r
+ android:textSize="16sp"\r
+ android:textStyle="bold"\r
+ android:typeface="sans" />\r
+\r
+ <ImageView\r
+ android:id="@+id/image"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="20dp"\r
+ android:layout_gravity="center_vertical"\r
+ android:layout_weight="0.1" />\r
+\r
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>\r
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"\r
+ android:layout_width="fill_parent"\r
+ android:layout_height="wrap_content"\r
+ android:orientation="vertical" >\r
+\r
+ <TextView\r
+ android:id="@+id/textViewItem"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:gravity="center_vertical"\r
+ android:paddingLeft="50dp"\r
+ android:text="Paired Items"\r
+ android:textColor="#545454"\r
+ android:textSize="15sp" />\r
+\r
+ <TextView\r
+ android:id="@+id/textViewSource"\r
+ android:layout_below="@id/textViewItem"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:gravity="center_vertical"\r
+ android:paddingLeft="50dp"\r
+ android:text="Paired Source"\r
+ android:textColor="#545454"\r
+ android:textSize="15sp" />\r
+\r
+ <TextView\r
+ android:id="@+id/textViewStatus"\r
+ android:layout_below="@id/textViewSource"\r
+ android:layout_width="wrap_content"\r
+ android:layout_height="wrap_content"\r
+ android:gravity="center_vertical"\r
+ android:paddingLeft="50dp"\r
+ android:text="Paired Status"\r
+ android:textColor="#545454"\r
+ android:textSize="15sp" />\r
+\r
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<menu xmlns:android="http://schemas.android.com/apk/res/android"\r
+ xmlns:app="http://schemas.android.com/apk/res-auto"\r
+ xmlns:tools="http://schemas.android.com/tools"\r
+ tools:context="org.iotivity.base.examples.MainActivity" >\r
+\r
+ <item\r
+ android:id="@+id/action_settings"\r
+ android:orderInCategory="100"\r
+ android:title="@string/action_settings"/>\r
+\r
+</menu>\r
--- /dev/null
+<resources>\r
+\r
+ <!--\r
+ Base application theme for API 11+. This theme completely replaces
+ AppBaseTheme from res/values/styles.xml on API 11+ devices.\r
+ -->\r
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+ <!-- API 11 theme customizations can go here. -->\r
+ </style>\r
+\r
+</resources>\r
--- /dev/null
+<resources>\r
+\r
+ <!--\r
+ Base application theme for API 14+. This theme completely replaces
+ AppBaseTheme from BOTH res/values/styles.xml and
+ res/values-v11/styles.xml on API 14+ devices.\r
+ -->\r
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+ <!-- API 14 theme customizations can go here. -->\r
+ </style>\r
+\r
+</resources>\r
--- /dev/null
+<resources>\r
+\r
+ <!--\r
+ Example customization of dimensions originally defined in res/values/dimens.xml
+ (such as screen margins) for screens with more than 820dp of available width. This
+ would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).\r
+ -->\r
+ <dimen name="activity_horizontal_margin">64dp</dimen>\r
+\r
+</resources>\r
--- /dev/null
+<resources>\r
+\r
+ <!-- Default screen margins, per the Android Design guidelines. -->\r
+ <dimen name="activity_horizontal_margin">16dp</dimen>\r
+ <dimen name="activity_vertical_margin">16dp</dimen>\r
+\r
+</resources>\r
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>\r
+\r
+ <string name="app_name">DirectPairingClient</string>\r
+ <string name="discover_items">Discover Resources</string>
+ <string name="paired_items">Paired Resources</string>
+ <string name="paired_list">Direct Paired Resources</string>\r
+ <string name="action_settings">Settings</string>\r
+\r
+</resources>\r
--- /dev/null
+<resources>\r
+\r
+ <!--\r
+ Base application theme, dependent on API level. This theme is replaced
+ by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\r
+ -->\r
+ <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">\r
+ <!--\r
+ Theme customizations available in newer API levels can go in
+ res/values-vXX/styles.xml, while customizations related to
+ backward-compatibility can go here.\r
+ -->\r
+ </style>\r
+\r
+ <!-- Application theme. -->\r
+ <style name="AppTheme" parent="AppBaseTheme">\r
+ <!-- All customizations that are NOT specific to a particular API-level can go here. -->\r
+ </style>\r
+\r
+</resources>\r
import org.iotivity.base.OcProvisioning;
import org.iotivity.base.OcSecureResource;
import org.iotivity.base.OicSecAcl;
+import org.iotivity.base.OicSecPdAcl;
+import org.iotivity.base.OcPrmType;
import org.iotivity.base.OxmType;
import org.iotivity.base.PlatformConfig;
import org.iotivity.base.ProvisionResult;
private List<OcSecureResource> deviceList;
private List<OcSecureResource> ownedDeviceList;
private TextView mEventsTextView;
+
+ OcSecureResource.ProvisionDirectPairingListener provisionDPListener =
+ new OcSecureResource.ProvisionDirectPairingListener() {
+ @Override
+ public void provisionDirectPairingListener(List<ProvisionResult> provisionResults,
+ int hasError) {
+ Log.d(TAG, "Inside provisionDPListener");
+ ProvisionResult pResult = provisionResults.get(0);
+ if (hasError == StringConstants.ERROR_CODE) {
+ logMessage(TAG + "Provision direct pairing Failed for " + pResult.getDevId());
+ } else {
+ logMessage(TAG + "Provision direct pairing Successful for " + pResult.getDevId());
+ }
+ }
+ };
+
OcSecureResource.ProvisionAclListener provisionAclListener =
new OcSecureResource.ProvisionAclListener() {
@Override
mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
);
filePath = getFilesDir().getPath() + "/"; // data/data/<package>/files/
//copy CBOR file when application runs first time
}
}
+
+ private void doDPProvisioning() {
+ try {
+ logMessage(TAG + "Provision direct pairing for " + ownedDeviceList.get(0).getDeviceID());
+ newSecureResource = ownedDeviceList.get(0);
+ String pin = "00000000";
+ List<OcPrmType>prmTypes = new ArrayList<OcPrmType>();
+ prmTypes.add(OcPrmType.DP_PRE_CONFIGURED);
+ boolean edp = true;
+ List<String> resources = new ArrayList<String>();
+ List<String> periods = new ArrayList<String>();
+ List<String> recurrences = new ArrayList<String>();
+ resources.add(StringConstants.DEFAULT_RESOURCES);
+ OicSecPdAcl pdAcl = new OicSecPdAcl(recurrences, periods,
+ StringConstants.DEFAULT_PERMISSION, resources);
+ OicSecPdAcl[] oicSecPdAcls = new OicSecPdAcl[1];
+ oicSecPdAcls[0] = pdAcl;
+ newSecureResource.doProvisionDirectPairing(pin, oicSecPdAcls, prmTypes, edp,
+ provisionDPListener);
+ } catch (Exception e) {
+ logMessage(TAG + "Direct Pairing Provisioning error: " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+
private void doPairwiseProvisioning() {
try {
logMessage(TAG + "Pairwise Provisioning b/w " + ownedDeviceList.get(0).getDeviceID()
if (ownedDeviceList.size() > 0) {
for (int i = 0; i < ownedDeviceList.size(); i++) {
publishProgress(TAG + "Owned Discovered Device " + (i + 1) + "= " +
- ownedDeviceList.get(i).getDeviceID()
- + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
- + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
- + "\nDevice Status= " + ((ownedDeviceList.get(i).
- getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
+ ownedDeviceList.get(i).getDeviceID()
+ + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
+ + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
+ + "\nDevice Status= " + ((ownedDeviceList.get(i).
+ getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
);
}
} else {
@Override
protected void onPostExecute(String s) {
+
+
+ if (ownedDeviceList.size() > 0 && "success".equals(s)) {
+ doDPProvisioning();
+ }
+
if (ownedDeviceList.size() > 1 && "success".equals(s)) {
doPairwiseProvisioning();
}
include ':simpleserver', ':simpleclient', ':fridgeserver', ':fridgeclient', ':guiclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':groupclient', ':groupserver', ':fridgegroupclient', ':fridgegroupserver', ':simplebase'
SECURED=System.getProperty('SECURE')
if(SECURED== "1"){
- include ':provisioningclient'
+ include ':provisioningclient', ':DirectPairing'
}
# Map of os and allowed archs (os: allowed archs)
os_arch_map = {
- 'linux': ['x86', 'x86_64', 'arm', 'arm64'],
- 'tizen': ['x86', 'x86_64', 'arm', 'arm64', 'armeabi-v7a'],
+ 'linux': ['x86', 'x86_64', 'arm', 'arm-v7a', 'arm64'],
+ 'tizen': ['x86', 'x86_64', 'arm', 'arm-v7a', 'armeabi-v7a', 'arm64'],
'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
'windows': ['x86', 'amd64', 'arm'],
'msys_nt':['x86', 'x86_64'],
WrapRequest *m_typeRequest;
};
-struct WrapRequest
+class WrapRequest
{
+public:
WrapRequest(WrapResource *wres, RequestType type, token_t token);
friend class WrapResource;
{
.deviceName = "IoTivity/Zigbee Server Sample",
.specVersion = "IoTivity/Zigbee Device Spec Version",
- .dataModleVersion = "IoTivity/Zigbee Data Model Version",
};
+ char *dmv = OICStrdup("IoTivity/Zigbee Data Model Version");
+ deviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+ deviceInfo.dataModelVersions->value = dmv;
char *dup = OICStrdup("oic.wk.d");
deviceInfo.types = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
deviceInfo.types->value = dup;
- OICFree(dup);
return OCSetDeviceInfo(deviceInfo);
}
}
#if defined(__ANDROID__) || _POSIX_TIMERS > 0
- #ifdef __ANDROID__
- if (camutex_condattr_setclock) {
+ #ifdef __ANDROID__
+ if (camutex_condattr_setclock)
+ {
ret = camutex_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
- #else
+ #else
{
ret = pthread_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
- #endif /* __ANDROID__ */
+ #endif /* __ANDROID__ */
if(0 != ret)
{
OIC_LOG_V(ERROR, TAG, "%s: Failed to set condition variable clock %d!",
struct timespec abstime;
#ifdef __ANDROID__
- if (camutex_cond_timedwait_relative) {
+ if (camutex_cond_timedwait_relative)
+ {
abstime.tv_sec = microseconds / USECS_PER_SEC;
abstime.tv_nsec = (microseconds % USECS_PER_SEC) * NANOSECS_PER_USECS;
//Wait for the given time
void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback);
/**
+ * Set this callback for receiving the changed connection information from peer devices.
+ *
+ * @param[in] callback Callback to be notified when connection state changes.
+ */
+void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler);
+
+/**
* API to send unicast TCP data.
*
* @param[in] endpoint complete network address to send to.
g_dtlsHandshakeCallback(&endpoint, &errorInfo);
}
}
- else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_CLOSE_NOTIFY == code)
+ else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_HANDSHAKE_FAILURE == code)
{
- OIC_LOG(INFO, NET_DTLS_TAG, "Peer closing connection");
+ OIC_LOG(INFO, NET_DTLS_TAG, "Failed to DTLS handshake, the peer will be removed.");
CARemovePeerFromPeerInfoList(peerAddr, port);
}
- else if(DTLS_ALERT_LEVEL_FATAL == level && DTLS_ALERT_HANDSHAKE_FAILURE == code)
+ else if(DTLS_ALERT_LEVEL_FATAL == level || DTLS_ALERT_CLOSE_NOTIFY == code)
{
- OIC_LOG(INFO, NET_DTLS_TAG, "Failed to DTLS handshake, the peer will be removed.");
+ OIC_LOG(INFO, NET_DTLS_TAG, "Peer closing connection");
CARemovePeerFromPeerInfoList(peerAddr, port);
}
return CA_STATUS_INVALID_PARAM;
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
CAResult_t CAEDRCreateJNIInterfaceObject(jobject context)
{
- JNIEnv* env;
+ JNIEnv* env = NULL;
OIC_LOG(DEBUG, TAG, "CAEDRCreateJNIInterfaceObject");
if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
OIC_LOG(DEBUG, TAG, "CAEDRTerminate");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL(data, TAG, "data is null");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
void CAEDRGetLocalAddress(char **address)
{
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL(data, TAG, "data is null");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL_VOID(data, TAG, "Invalid thread context");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL_VOID(data, TAG, "data is null");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
CAResult_t CAEDRServerStartAcceptThread()
{
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
return;
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth initialization failed!, error num [%x]",
ret);
- return;
+ return CA_STATUS_FAILED;
}
ret = bt_adapter_set_state_changed_cb(CAEDRAdapterStateChangeCallback, NULL);
if(BT_ERROR_NONE != ret)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "bt_adapter_set_state_changed_cb failed");
- return;
+ return CA_STATUS_FAILED;
}
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
(void)object;
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
// reset send state
- ret = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE,
- STATE_SEND_NONE);
- if (CA_STATUS_OK != ret)
+ CAResult_t resetRet = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE,
+ STATE_SEND_NONE);
+ if (CA_STATUS_OK != resetRet)
{
- OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
+ OIC_LOG_V(ERROR, TAG, "CALEClientUpdateDeviceState has failed (%d)", resetRet);
+ ret = CA_SEND_FAILED;
}
return ret;
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL_VOID(object, TAG, "object is null");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
}
-static jstring CALEClientGetAddressFromGatt(JNIEnv *env, jobject gatt)
-{
- OIC_LOG(DEBUG, TAG, "IN - CAManagerGetAddressFromGatt");
-
- VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
- VERIFY_NON_NULL_RET(gatt, TAG, "gatt is null", NULL);
-
- jmethodID jni_mid_getDevice = CAGetJNIMethodID(env, CLASSPATH_BT_GATT,
- "getDevice", METHODID_BT_DEVICE);
- if (!jni_mid_getDevice)
- {
- OIC_LOG(ERROR, TAG, "jni_mid_getDevice is null");
- return NULL;
- }
-
- jobject jni_obj_device = (*env)->CallObjectMethod(env, gatt, jni_mid_getDevice);
- if (!jni_obj_device)
- {
- OIC_LOG(ERROR, TAG, "jni_obj_device is null");
- return NULL;
- }
-
- jstring jni_address = CALEGetAddressFromBTDevice(env, jni_obj_device);
- if (!jni_address)
- {
- OIC_LOG(ERROR, TAG, "jni_address is null");
- return NULL;
- }
-
- OIC_LOG(DEBUG, TAG, "OUT - CAManagerGetAddressFromGatt");
- return jni_address;
-}
-
/*
* Class: org_iotivity_ca_jar_caleinterface
* Method: CALeGattConnectionStateChangeCallback
}
OIC_LOG_V(DEBUG, TAG, "CALeGattConnectionStateChangeCallback - address [%s]", address);
- CAResult_t res;
if (state_connected == newstate)
{
OIC_LOG(DEBUG, TAG, "LE is connected");
if (GATT_SUCCESS == status)
{
- res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, STATE_CONNECTED);
+ CAResult_t res = CALEClientUpdateDeviceState(address,
+ CA_LE_CONNECTION_STATE,
+ STATE_CONNECTED);
(*env)->ReleaseStringUTFChars(env, jni_address, address);
if (CA_STATUS_OK != res)
{
{
OIC_LOG(DEBUG, TAG, "LE is disconnected");
- res = CALEClientUpdateDeviceState(address, CA_LE_CONNECTION_STATE, STATE_DISCONNECTED);
+ CAResult_t res = CALEClientUpdateDeviceState(address,
+ CA_LE_CONNECTION_STATE,
+ STATE_DISCONNECTED);
(*env)->ReleaseStringUTFChars(env, jni_address, address);
if (CA_STATUS_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
return CA_STATUS_FAILED;
}
+ // If we didn't send the last block message and received EMPTY message,
+ // we have to remain the block data from list.
+ CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+ if (data && (data->block1.m || data->block2.m))
+ {
+ OIC_LOG(DEBUG, TAG, "this is normal EMPTY message for blockwise-transfer.");
+ CADestroyBlockID(blockDataID);
+ return CA_STATUS_OK;
+ }
+
CARemoveBlockDataFromList(blockDataID);
CADestroyBlockID(blockDataID);
return CA_NOT_SUPPORTED;
return CA_STATUS_FAILED;
}
- if (data->requestInfo)
- {
- data->requestInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
- }
-
if (data->responseInfo)
{
+ data->responseInfo->info.type =
+ (pdu->hdr->coap_hdr_udp_t.type == CA_MSG_CONFIRM) ?
+ CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM;
data->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
- }
- res = CAAddSendThreadQueue(data, blockID);
- if (CA_STATUS_OK != res)
- {
- OIC_LOG(ERROR, TAG, "add has failed");
- return res;
+ res = CAAddSendThreadQueue(data, blockID);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "add has failed");
+ return res;
+ }
}
-
break;
case CA_OPTION1_RESPONSE:
return CA_STATUS_OK;
}
+static CAResult_t CASendDirectEmptyResponse(const CAEndpoint_t *endpoint, uint16_t messageId)
+{
+ OIC_LOG(DEBUG, TAG, "Entering CASendDirectEmptyResponse");
+ CAResponseInfo_t respInfo = {
+ .result = CA_EMPTY
+ };
+ respInfo.info.type = CA_MSG_ACKNOWLEDGE;
+ respInfo.info.messageId = messageId;
+
+ CAResult_t caResult = CASendResponse(endpoint, &respInfo);
+
+ OIC_LOG(DEBUG, TAG, "Exit CASendDirectEmptyResponse");
+ return caResult;
+}
+
CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
const CABlockDataID_t *blockID)
{
}
else
{
- OIC_LOG(DEBUG, TAG, "need new msgID");
+ // if the received response message type is CON, send empty message.
+ // and then, send next block request message with new messagId.
+ if (msgType == CA_MSG_CONFIRM)
+ {
+ CASendDirectEmptyResponse(data->remoteEndpoint,
+ data->requestInfo->info.messageId);
+ sentMsgType = CA_MSG_CONFIRM;
+ }
+
if (data->requestInfo)
{
+ OIC_LOG(DEBUG, TAG, "need new msgID");
data->requestInfo->info.messageId = 0;
data->requestInfo->info.type = sentMsgType;
}
return CA_STATUS_OK;
}
+static CABlockData_t* CACheckTheExistOfBlockData(const CABlockDataID_t* blockDataID,
+ coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
+ uint8_t blockType)
+{
+ // Get BlockData data. If does not exist, create a new data
+ CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+ if (!data)
+ {
+ OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
+
+ CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
+ if (!cadata)
+ {
+ OIC_LOG(ERROR, TAG, "data is null");
+ return NULL;
+ }
+
+ data = CACreateNewBlockData(cadata);
+ if (!data)
+ {
+ OIC_LOG(ERROR, TAG, "failed to create a new block data");
+ CADestroyDataSet(cadata);
+ return NULL;
+ }
+ CADestroyDataSet(cadata);
+ }
+
+ // update BLOCK OPTION type
+ CAResult_t res = CAUpdateBlockOptionType(blockDataID, blockType);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "update has failed");
+ return NULL;
+ }
+
+ return data;
+}
+
// TODO make pdu const after libcoap is updated to support that.
CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
const CAData_t *receivedData, coap_block_t block,
return CA_STATUS_FAILED;
}
- // Get BlockData data. If does not exist, create a new data
- CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+ CABlockData_t *data = CACheckTheExistOfBlockData(blockDataID, pdu, endpoint,
+ COAP_OPTION_BLOCK1);
if (!data)
{
- OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
-
- CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
- if (!cadata)
- {
- OIC_LOG(ERROR, TAG, "data is null");
- CADestroyBlockID(blockDataID);
- return CA_STATUS_FAILED;
- }
-
- data = CACreateNewBlockData(cadata);
- if (!data)
- {
- OIC_LOG(ERROR, TAG, "failed to create a new block data");
- CADestroyDataSet(cadata);
- CADestroyBlockID(blockDataID);
- return CA_STATUS_FAILED;
- }
- CADestroyDataSet(cadata);
- }
-
- // update BLOCK OPTION1 type
- CAResult_t res = CAUpdateBlockOptionType(blockDataID, COAP_OPTION_BLOCK1);
- if (CA_STATUS_OK != res)
- {
- OIC_LOG(ERROR, TAG, "update has failed");
+ OIC_LOG(ERROR, TAG, "Failed to create or get block data");
goto exit;
}
+ CAResult_t res = CA_STATUS_OK;
uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
{
OIC_LOG_V(DEBUG, TAG, "M bit is %d", block.m);
- if (0 == block.m)
- {
- // Last block is received
- blockWiseStatus = CA_OPTION1_REQUEST_LAST_BLOCK;
- }
- else
- {
- blockWiseStatus = CA_OPTION1_REQUEST_BLOCK;
- }
+ blockWiseStatus = (0 == block.m) ?
+ CA_OPTION1_REQUEST_LAST_BLOCK : CA_OPTION1_REQUEST_BLOCK;
}
}
else
return CA_STATUS_FAILED;
}
- // Get BlockData data. If does not exist, create a new data
- CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
+ CABlockData_t *data = CACheckTheExistOfBlockData(blockDataID, pdu, endpoint,
+ COAP_OPTION_BLOCK2);
if (!data)
{
- OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
-
- CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
- if (!cadata)
- {
- OIC_LOG(ERROR, TAG, "data is null");
- CADestroyBlockID(blockDataID);
- return CA_STATUS_FAILED;
- }
-
- data = CACreateNewBlockData(cadata);
- if (!data)
- {
- OIC_LOG(ERROR, TAG, "failed to create a new block data");
- CADestroyDataSet(cadata);
- CADestroyBlockID(blockDataID);
- return CA_STATUS_FAILED;
- }
- CADestroyDataSet(cadata);
- }
-
- // set Block Option Type
- CAResult_t res = CAUpdateBlockOptionType(blockDataID, COAP_OPTION_BLOCK2);
- if (CA_STATUS_OK != res)
- {
- OIC_LOG(ERROR, TAG, "update has failed");
+ OIC_LOG(ERROR, TAG, "Failed to create or get block data");
goto exit;
}
+ CAResult_t res = CA_STATUS_OK;
uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
if (0 == block.num && CA_GET == pdu->hdr->coap_hdr_udp_t.code && 0 == block.m)
{
CAGetResponseInfoFromPDU(pdu, resInfo, endpoint);
requestInfo->method = CA_GET;
+ requestInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu->hdr, pdu->length);
requestInfo->info.resourceUri = OICStrdup(resInfo->info.resourceUri);
// after copying the resource uri, destroy response info.
return CA_STATUS_OK;
}
-CAResult_t CAUpdateBlockOptionType(const CABlockDataID_t *blockID,
- uint8_t blockType)
+CAResult_t CAUpdateBlockOptionType(const CABlockDataID_t *blockID, uint8_t blockType)
{
OIC_LOG(DEBUG, TAG, "IN-UpdateBlockOptionType");
VERIFY_NON_NULL(blockID, TAG, "blockID");
VERIFY_NON_NULL(sendData, TAG, "sendData");
VERIFY_NON_NULL(blockData, TAG, "blockData");
- CABlockDataID_t* blockDataID;
- if(sendData->requestInfo)
- {
- blockDataID = CACreateBlockDatablockId(
- (CAToken_t)sendData->requestInfo->info.token,
- sendData->requestInfo->info.tokenLength,
- sendData->remoteEndpoint->port);
- }
- else if(sendData->responseInfo)
- {
- blockDataID = CACreateBlockDatablockId(
- (CAToken_t)sendData->responseInfo->info.token,
- sendData->responseInfo->info.tokenLength,
- sendData->remoteEndpoint->port);
- }
- else
+ if (sendData->responseInfo)
{
- OIC_LOG(ERROR, TAG, "sendData doesn't have requestInfo or responseInfo");
- return CA_STATUS_FAILED;
- }
-
- if (NULL == blockDataID || blockDataID->idLength < 1)
- {
- OIC_LOG(ERROR, TAG, "blockId is null");
- CADestroyBlockID(blockDataID);
- return CA_STATUS_FAILED;
- }
-
- ca_mutex_lock(g_context.blockDataListMutex);
-
- size_t len = u_arraylist_length(g_context.dataList);
- for (size_t i = 0; i < len; i++)
- {
- CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
- if (!currData)
+ CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
+ (CAToken_t)sendData->responseInfo->info.token,
+ sendData->responseInfo->info.tokenLength,
+ sendData->remoteEndpoint->port);
+ if (NULL == blockDataID || blockDataID->idLength < 1)
{
- continue;
+ OIC_LOG(ERROR, TAG, "blockId is null");
+ CADestroyBlockID(blockDataID);
+ return CA_STATUS_FAILED;
}
- if (sendData->requestInfo) // sendData is requestMessage
- {
- OIC_LOG(DEBUG, TAG, "Send request");
- if (NULL != currData->blockDataId
- && NULL != currData->blockDataId->id
- && currData->blockDataId->idLength > 0
- && NULL != sendData->requestInfo->info.token)
- {
- if (CABlockidMatches(currData, blockDataID))
- {
- OIC_LOG(ERROR, TAG, "already sent");
- continue;
- }
- }
- }
- else if (sendData->responseInfo) // sendData is responseMessage
+ CABlockData_t *storedData = CAGetBlockDataFromBlockDataList(blockDataID);
+ if (storedData)
{
- OIC_LOG(DEBUG, TAG, "Send response");
- if (NULL != currData->blockDataId
- && NULL != currData->blockDataId->id
- && currData->blockDataId->idLength > 0
- && NULL != sendData->responseInfo->info.token)
+ OIC_LOG(DEBUG, TAG, "Send response about the received block request.");
+ if (storedData->sentData)
{
- if (CABlockidMatches(currData, blockDataID))
- {
- // set sendData
- if (NULL != currData->sentData)
- {
- OIC_LOG(DEBUG, TAG, "init block number");
- CADestroyDataSet(currData->sentData);
- }
- currData->sentData = CACloneCAData(sendData);
- *blockData = currData;
- ca_mutex_unlock(g_context.blockDataListMutex);
- CADestroyBlockID(blockDataID);
- return CA_STATUS_OK;
- }
+ OIC_LOG(DEBUG, TAG, "init block number");
+ CADestroyDataSet(storedData->sentData);
}
+ storedData->sentData = CACloneCAData(sendData);
+ *blockData = storedData;
+ CADestroyBlockID(blockDataID);
+ return CA_STATUS_OK;
}
- else
- {
- OIC_LOG(ERROR, TAG, "no CAInfo data");
- continue;
- }
+ CADestroyBlockID(blockDataID);
}
- ca_mutex_unlock(g_context.blockDataListMutex);
-
- CADestroyBlockID(blockDataID);
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, TAG, "CAStartListeningServer");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CAStopListeningServer");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CAStartDiscoveryServer");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CARegisterHandler");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
OIC_LOG(DEBUG, TAG, "CA is not initialized");
return;
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSHandshakeCallback");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSX509CredentialsHandler");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSCrlHandler");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CAGetNetworkInformation");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CASendRequest");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG(DEBUG, TAG, "CASendResponse");
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG_V(DEBUG, TAG, "Selected network : %d", interestedNetwork);
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
{
OIC_LOG_V(DEBUG, TAG, "unselected network : %d", nonInterestedNetwork);
- if(!g_isInitialized)
+ if (!g_isInitialized)
{
return CA_STATUS_NOT_INITIALIZED;
}
static void CARegisterCallback(CAConnectivityHandler_t handler)
{
- if(handler.startAdapter == NULL ||
+ if (handler.startAdapter == NULL ||
handler.startListenServer == NULL ||
handler.stopListenServer == NULL ||
handler.startDiscoveryServer == NULL ||
{
void* ptrType = u_arraylist_get(list, i);
- if(NULL == ptrType)
+ if (NULL == ptrType)
{
continue;
}
int index = CAGetAdapterIndex(connType);
if (0 > index)
- if (-1 == index)
{
- OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+ OIC_LOG(ERROR, TAG, "unknown connectivity type!");
continue;
}
}
OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
- CAResult_t result;
- if(CA_RESPONSE_DATA == dataType)
+ if (CA_RESPONSE_DATA == dataType)
{
CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
if (!resInfo)
return NULL;
}
- result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
+ CAResult_t result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
return NULL;
}
- result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
+ CAResult_t result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
coap_pdu_t *pdu = NULL;
CAInfo_t *info = NULL;
coap_list_t *options = NULL;
- coap_transport_type transport;
+ coap_transport_type transport = coap_udp;
CAResult_t res = CA_SEND_FAILED;
if (NULL != data->requestInfo)
{
coap_pdu_t *pdu = NULL;
CAInfo_t *info = NULL;
coap_list_t *options = NULL;
- coap_transport_type transport;
+ coap_transport_type transport = coap_udp;
if (SEND_TYPE_UNICAST == type)
{
OIC_LOG(DEBUG,TAG,"Unicast message");
+
#ifdef ROUTING_GATEWAY
/*
* When forwarding a packet, do not attempt retransmission as its the responsibility of
return NULL;
}
- if(CA_REQUEST_DATA == dataType)
+ if (CA_REQUEST_DATA == dataType)
{
// clone request info
CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
- if(!request)
+ if (!request)
{
OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
goto exit;
cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
cadata->requestInfo = request;
}
- else if(CA_RESPONSE_DATA == dataType)
+ else if (CA_RESPONSE_DATA == dataType)
{
// clone response info
CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
#ifdef SINGLE_THREAD
CAResult_t result = CAProcessSendData(data);
- if(CA_STATUS_OK != result)
+ if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
CADestroyData(data, sizeof(CAData_t));
{
// send block data
CAResult_t res = CASendBlockWiseData(data);
- if(CA_NOT_SUPPORTED == res)
+ if (CA_NOT_SUPPORTED == res)
{
OIC_LOG(DEBUG, TAG, "normal msg will be sent");
CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
static void CALogPayloadInfo(CAInfo_t *info)
{
- if(info)
+ if (info)
{
if (info->options)
{
#define TAG "OIC_CA_PRTCL_MSG"
-#define CA_BUFSIZE (128)
#define CA_PDU_MIN_SIZE (4)
#define CA_ENCODE_BUFFER_SIZE (4)
#endif
{
OIC_LOG_V(DEBUG, TAG, "msgID is %d", info->messageId);
- uint16_t message_id;
+ uint16_t message_id = 0;
if (0 == info->messageId)
{
/* initialize message id */
}
else if (str && length)
{
- unsigned char uriBuffer[CA_BUFSIZE] = { 0 };
+ unsigned char uriBuffer[CA_MAX_URI_LENGTH] = { 0 };
unsigned char *pBuf = uriBuffer;
size_t buflen = sizeof(uriBuffer);
int res = (target == COAP_OPTION_URI_PATH) ? coap_split_path(str, length, pBuf, &buflen) :
uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
{
uint32_t count = 0;
- coap_opt_t *option;
+ coap_opt_t *option = NULL;
while ((option = coap_option_next(&opt_iter)))
{
}
}
- coap_opt_t *option;
+ coap_opt_t *option = NULL;
char optionResult[CA_MAX_URI_LENGTH] = {0};
uint32_t idx = 0;
uint32_t optionLength = 0;
VERIFY_NON_NULL(outInfo, TAG, "outInfo");
VERIFY_NON_NULL(endpoint, TAG, "endpoint");
- coap_transport_type transport;
+ coap_transport_type transport = coap_udp;
#ifdef WITH_TCP
if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
{
transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu_hdr)[0] >> 4);
}
- else
#endif
- {
- transport = coap_udp;
- }
unsigned char* token = NULL;
unsigned int token_length = 0;
// should remain that way so a 0 byte of length 1 is inserted.
len = 1;
option[0]=0;
- } else {
+ }
+ else
+ {
memcpy(option, data, len);
option[len] = '\0';
}
if (NULL == thread)
{
OIC_LOG(ERROR, TAG, "thread data passing error!!");
-
return;
}
thread->isStop = true;
thread->threadTask = task;
thread->destroy = destroy;
- if(NULL == thread->dataQueue || NULL == thread->threadMutex || NULL == thread->threadCond)
+ if (NULL == thread->dataQueue || NULL == thread->threadMutex || NULL == thread->threadCond)
+ {
goto ERROR_MEM_FAILURE;
+ }
return CA_STATUS_OK;
- ERROR_MEM_FAILURE:
- if(thread->dataQueue)
+
+ERROR_MEM_FAILURE:
+ if (thread->dataQueue)
{
u_queue_delete(thread->dataQueue);
thread->dataQueue = NULL;
}
- if(thread->threadMutex)
+ if (thread->threadMutex)
{
ca_mutex_free(thread->threadMutex);
thread->threadMutex = NULL;
}
- if(thread->threadCond)
+ if (thread->threadCond)
{
ca_cond_free(thread->threadCond);
thread->threadCond = NULL;
}
return CA_MEMORY_ALLOC_FAILED;
-
}
CAResult_t CAQueueingThreadStart(CAQueueingThread_t *thread)
u_queue_message_t *message = u_queue_get_element(thread->dataQueue);
// free
- if(NULL != message)
+ if (NULL != message)
{
if (NULL != thread->destroy)
{
#include "caremotehandler.h"
#include "caprotocolmessage.h"
#include "oic_malloc.h"
+#include "ocrandom.h"
#include "logger.h"
#define TAG "OIC_CA_RETRANS"
*/
static uint64_t CAGetTimeoutValue()
{
-#if !defined(_WIN32)
- return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
+#ifdef HAVE_SRANDOM
+ return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
(uint64_t) 1000;
#else
- return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (rand() & 0xFF)) >> 8)) *
+ return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
(uint64_t) 1000;
#endif
}
caglobals.ip.nm.numIfItems = 0;
for (size_t i = 0; i < interfaces; i++)
{
- CAResult_t result = CA_STATUS_OK;
struct ifreq* item = &ifr[i];
char *name = item->ifr_name;
struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
}
// Add IPv4 interface
- result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
+ CAResult_t result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
if (CA_STATUS_OK != result)
{
goto exit;
return CA_STATUS_FAILED;
}
- JNIEnv* env;
+ JNIEnv* env = NULL;
if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
{
OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
}
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags)
{
- char recvBuffer[COAP_MAX_PDU_SIZE];
+ char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
size_t len;
int level, type, namelen;
VERIFY_NON_NULL(g_jvm, TAG, "g_jvm");\r
\r
bool isAttached = false;\r
- JNIEnv* env;\r
+ JNIEnv* env = NULL;\r
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
if (JNI_OK != res)\r
{\r
\r
OIC_LOG(INFO, TAG, "CANFCStartServer : IN");\r
\r
- JNIEnv* env;\r
+ JNIEnv* env = NULL;\r
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
if (JNI_OK != res)\r
{\r
\r
OIC_LOG(INFO, TAG, "CANfcSendDataImpl moved env outside");\r
bool isAttached = false;\r
- JNIEnv* env;\r
+ JNIEnv* env = NULL;\r
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);\r
if (JNI_OK != res)\r
{\r
static int CACreateAcceptSocket(int family, CASocket_t *sock);
static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
static void CAFindReadyMessage();
-static void CASelectReturned(fd_set *readFds, int ret);
+static void CASelectReturned(fd_set *readFds);
static void CAReceiveMessage(int fd);
static void CAReceiveHandler(void *data);
static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
return;
}
- CASelectReturned(&readFds, ret);
+ CASelectReturned(&readFds);
}
-static void CASelectReturned(fd_set *readFds, int ret)
+static void CASelectReturned(fd_set *readFds)
{
VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
class CABlockTransferTests : public testing::Test {
protected:
- virtual void SetUp() {
+ virtual void SetUp()
+ {
CAInitialize();
}
static void CABTPaitingCreateJNIInterfaceObject(jobject context)
{
- JNIEnv* env;
+ JNIEnv* env = NULL;
OIC_LOG(INFO, TAG, "OICEDRCreateJNIInterfaceObject");
if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
VERIFY_NON_NULL(address, TAG, "address");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
VERIFY_NON_NULL(address, TAG, "address");
bool isAttached = false;
- JNIEnv* env;
+ JNIEnv* env = NULL;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
if (JNI_OK != res)
{
* @param cred is the pointer to instance of OicSecCred_t structure.
* @param cborPayload is the CBOR converted value.
* @param cborSize is the size of the CBOR.
+ * @param secureFlag shows fill or not private key.
*
* @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
*/
OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
- size_t *cborSize);
+ size_t *cborSize, int secureFlag);
/**
* This function generates the bin credential data.
extern const char * SVR_DB_FILE_NAME;
extern const char * SVR_DB_DAT_FILE_NAME;
-extern const char * OIC_MI_DEF;
//AMACL
extern const char * OIC_RSRC_TYPE_SEC_AMACL;
OIC_OXM_COUNT
}OicSecOxm_t;
+typedef enum
+{
+ OIC_ENCODING_UNKNOW = 0,
+ OIC_ENCODING_RAW = 1,
+ OIC_ENCODING_BASE64 = 2
+}OicEncodingType_t;
+
typedef struct OicSecKey OicSecKey_t;
typedef struct OicSecPstat OicSecPstat_t;
{
uint8_t *data;
size_t len;
+
+ // TODO: This field added as workaround. Will be replaced soon.
+ OicEncodingType_t encoding;
+
};
/**
'../../../c_common/ocrandom/include',
'../../logger/include',
'../../../oc_logger/include',
- '../../ocmalloc/include',
+ '../../../c_common/oic_malloc/include',
'include',
'include/internal',
'include/oxm',
'../../resource/csdk/security/include',
'../../../../extlibs/cjson/',
- '../../../../../extlibs/tinydtls/',
+ '../../../../extlibs/tinydtls/',
'../../connectivity/inc',
'../../connectivity/external/inc',
'../../connectivity/common/inc',
#define MAX_URI_LENGTH (64)
#define MAX_PERMISSION_LENGTH (5)
+#define MAX_ACL_LENGTH 100
#define CREATE (1)
#define READ (2)
#define UPDATE (4)
*/
static void deleteACL(OicSecAcl_t *acl)
{
- if (acl)
+ if (acl && MAX_ACL_LENGTH > acl->resourcesLen)
{
/* Clean Resources */
for (size_t i = 0; i < (acl)->resourcesLen; i++)
//Set Resource.
printf("Num. of Resource : \n");
ret = scanf("%zu", &acl->resourcesLen);
- if(-1 == ret)
+ if(-1 == ret || MAX_ACL_LENGTH < acl->resourcesLen)
{
printf("Error while input\n");
return -1;
******************************************************************/
-#include <oic_malloc.h>
#include <gtest/gtest.h>
#include "ckm_info.h"
ASSERT_EQ(PKI_SUCCESS, SetCAPrivateKey(&CKMInfoTest::privateKey));
ByteArray privateKey = {0,0};
- privateKey.data = (uint8_t*)OICMalloc(PRIVATE_KEY_SIZE);
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+ privateKey.data = caPrivKey;
privateKey.len = PRIVATE_KEY_SIZE;
- EXPECT_TRUE(NULL != privateKey.data);
EXPECT_EQ(PKI_SUCCESS, GetCAPrivateKey(&privateKey));
EXPECT_TRUE(0 == memcmp(CKMInfoTest::privateKey.data, privateKey.data, PRIVATE_KEY_SIZE));
- OICFree(privateKey.data);
}
//SetGetCAPublicKey test
ASSERT_EQ(PKI_SUCCESS, SetCAPublicKey(&CKMInfoTest::publicKey));
ByteArray publicKey = {0,0};
- publicKey.data = (uint8_t*)OICMalloc(PUBLIC_KEY_SIZE);
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+
+ publicKey.data = caPubKey;
publicKey.len = PUBLIC_KEY_SIZE;
- EXPECT_TRUE(NULL != publicKey.data);
EXPECT_EQ(PKI_SUCCESS, GetCAPublicKey(&publicKey));
EXPECT_TRUE(0 == memcmp(CKMInfoTest::publicKey.data, publicKey.data, PUBLIC_KEY_SIZE));
- OICFree(publicKey.data);
}
//SetGetCAName test
ASSERT_EQ(PKI_SUCCESS, SetCAName(&CKMInfoTest::caName));
ByteArray caName = {0,0};
- caName.data = (uint8_t*)OICMalloc(ISSUER_NAME_SIZE);
+ uint8_t caIssName[PUBLIC_KEY_SIZE] = {0};
+
+ caName.data = caIssName;
caName.len = ISSUER_NAME_SIZE;
- EXPECT_TRUE(NULL != caName.data);
EXPECT_EQ(PKI_SUCCESS, GetCAName(&caName));
EXPECT_TRUE(0 == memcmp(CKMInfoTest::caName.data, caName.data, ISSUER_NAME_SIZE));
- OICFree(caName.data);
}
//SetGetCKMInfo test
long serialNum = 0;
ByteArray publicKey = {0,0};
- publicKey.data = (uint8_t*)OICMalloc(PUBLIC_KEY_SIZE);
+ uint8_t caIssName[ISSUER_MAX_CERT_SIZE] = {0};
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+ publicKey.data = caPubKey;
publicKey.len = PUBLIC_KEY_SIZE;
- EXPECT_TRUE(NULL != publicKey.data);
ByteArray privateKey = {0,0};
- privateKey.data = (uint8_t*)OICMalloc(PRIVATE_KEY_SIZE);
+ privateKey.data = caPrivKey;
privateKey.len = PRIVATE_KEY_SIZE;
- EXPECT_TRUE(NULL != privateKey.data);
ByteArray caName = {0,0};
- caName.data = (uint8_t*)OICMalloc(ISSUER_NAME_SIZE);
+ caName.data = caIssName;
caName.len = ISSUER_NAME_SIZE;
- EXPECT_TRUE(NULL != caName.data);
EXPECT_EQ(PKI_SUCCESS, GetCKMInfo(&nSn, &serialNum,
&privateKey, &publicKey, &caName));
EXPECT_TRUE(0 == memcmp(CKMInfoTest::privateKey.data, privateKey.data, PRIVATE_KEY_SIZE));
EXPECT_TRUE(0 == memcmp(CKMInfoTest::publicKey.data, publicKey.data, PUBLIC_KEY_SIZE));
EXPECT_TRUE(0 == memcmp(CKMInfoTest::caName.data, caName.data, ISSUER_NAME_SIZE));
-
- OICFree(publicKey.data);
- OICFree(privateKey.data);
- OICFree(caName.data);
}
//SetGetCACertificate test
ASSERT_EQ(PKI_SUCCESS, SetCACertificate(&CKMInfoTest::derCode));
ByteArray der = {0,0};
- der.data = (uint8_t*)OICMalloc(CERT_LEN);
+ uint8_t caCert[CERT_LEN] = {0};
+ der.data = caCert;
der.len = CERT_LEN;
EXPECT_TRUE(NULL != der.data);
EXPECT_EQ(PKI_SUCCESS, GetCACertificate(&der));
EXPECT_TRUE(0 == memcmp(CKMInfoTest::derCode.data, der.data, CERT_LEN));
-
- OICFree(der.data);
}
//SetGetCRLSerialNumber test
#include "ocstack.h"
#include "securevirtualresourcetypes.h"
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
/**
* Function to generate credentials according to the type.
*
*/
OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
OicSecAcl_t *acl, OCProvisionResultCB resultCallback);
-
+
+/**
+ * API to request CRED information to resource.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] resultCallback callback provided by API user, callback will be called when
+ * provisioning request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OCProvisionResultCB resultCallback);
+
+/**
+ * API to request ACL information to resource.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] resultCallback callback provided by API user, callback will be called when
+ * provisioning request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OCProvisionResultCB resultCallback);
+
#ifdef __WITH_X509__
/**
* API to send CRL information to resource.
OCProvisionResultCB resultCallback);\r
\r
/**\r
+ * this function requests CRED information to resource.\r
+ *\r
+ * @param[in] ctx Application context would be returned in result callback.\r
+ * @param[in] selectedDeviceInfo Selected target device.\r
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning\r
+ request recieves a response from resource server.\r
+ * @return OC_STACK_OK in case of success and other value otherwise.\r
+ */\r
+OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,\r
+ OCProvisionResultCB resultCallback);\r
+\r
+/**\r
+ * this function requests ACL information to resource.\r
+ *\r
+ * @param[in] ctx Application context would be returned in result callback.\r
+ * @param[in] selectedDeviceInfo Selected target device.\r
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning\r
+ request recieves a response from resource server.\r
+ * @return OC_STACK_OK in case of success and other value otherwise.\r
+ */\r
+OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,\r
+ OCProvisionResultCB resultCallback);\r
+\r
+/**\r
* this function sends Direct-Pairing Configuration to a device.\r
*\r
* @param[in] ctx Application context would be returned in result callback.\r
#define _34_CHECK_LINK_STATUS_ 34
#define _40_UNLINK_PAIR_DEVS_ 40
#define _50_REMOVE_SELEC_DEV_ 50
+#define _60_GET_CRED_ 60
+#define _61_GET_ACL_ 61
#define _99_EXIT_PRVN_CLT_ 99
#define ACL_RESRC_MAX_NUM 16
g_doneCB = true;
}
+static void getCredCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
+{
+ if(!hasError)
+ {
+ OIC_LOG_V(INFO, TAG, "getCredCB SUCCEEDED - ctx: %s", (char*) ctx);
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "getCredCB FAILED - ctx: %s", (char*) ctx);
+ printResultList((const OCProvisionResult_t*) arr, nOfRes);
+ }
+ g_doneCB = true;
+}
+
+static void getAclCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
+{
+ if(!hasError)
+ {
+ OIC_LOG_V(INFO, TAG, "getAclCB SUCCEEDED - ctx: %s", (char*) ctx);
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "getAclCB FAILED - ctx: %s", (char*) ctx);
+ printResultList((const OCProvisionResult_t*) arr, nOfRes);
+ }
+ g_doneCB = true;
+}
+
static void provisionDPCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
{
if(!hasError)
return -1;
}
+static int getCred(void)
+{
+ // check |own_list| for checking selected link status on PRVN DB
+ if(!g_own_list || 1>g_own_cnt)
+ {
+ printf(" > Owned Device List, to Check Linked Status on PRVN DB, is Empty\n");
+ printf(" > Please Register Unowned Devices first, with [20] Menu\n");
+ return 0; // normal case
+ }
+
+ // select device for checking selected link status on PRVN DB
+ int dev_num = 0;
+ for( ; ; )
+ {
+ printf(" > Enter Device Number, for Checking Linked Status on PRVN DB: ");
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%d", &dev_num);
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ if(0<dev_num && g_own_cnt>=dev_num)
+ {
+ break;
+ }
+ printf(" Entered Wrong Number. Please Enter Again\n");
+ }
+
+ // call |getDevInst| API actually
+ // calling this API with callback actually acts like blocking
+ // for error checking, the return value saved and printed
+ g_doneCB = false;
+ OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*) g_own_list, dev_num);
+ if(!dev)
+ {
+ OIC_LOG(ERROR, TAG, "getDevInst: device instance empty");
+ goto PVACL_ERROR;
+ }
+ OCStackResult rst = OCGetCredResource((void*) g_ctx, dev, getCredCB);
+ if(OC_STACK_OK != rst)
+ {
+ OIC_LOG_V(ERROR, TAG, "OCGetCred API error: %d", rst);
+ goto PVACL_ERROR;
+ }
+ if(waitCallbackRet()) // input |g_doneCB| flag implicitly
+ {
+ OIC_LOG(ERROR, TAG, "OCGetCredResource callback error");
+ goto PVACL_ERROR;
+ }
+
+ // display the result of get credential
+ printf(" > Get Cred SUCCEEDED\n");
+
+ return 0;
+
+PVACL_ERROR:
+ return -1;
+}
+
+static int getAcl(void)
+{
+ // check |own_list| for checking selected link status on PRVN DB
+ if(!g_own_list || 1>g_own_cnt)
+ {
+ printf(" > Owned Device List, to Check Linked Status on PRVN DB, is Empty\n");
+ printf(" > Please Register Unowned Devices first, with [20] Menu\n");
+ return 0; // normal case
+ }
+
+ // select device for checking selected link status on PRVN DB
+ int dev_num = 0;
+ for( ; ; )
+ {
+ printf(" > Enter Device Number, for Checking Linked Status on PRVN DB: ");
+ for(int ret=0; 1!=ret; )
+ {
+ ret = scanf("%d", &dev_num);
+ for( ; 0x20<=getchar(); ); // for removing overflow garbages
+ // '0x20<=code' is character region
+ }
+ if(0<dev_num && g_own_cnt>=dev_num)
+ {
+ break;
+ }
+ printf(" Entered Wrong Number. Please Enter Again\n");
+ }
+
+ // call |getDevInst| API actually
+ // calling this API with callback actually acts like blocking
+ // for error checking, the return value saved and printed
+ g_doneCB = false;
+ OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*) g_own_list, dev_num);
+ if(!dev)
+ {
+ OIC_LOG(ERROR, TAG, "getDevInst: device instance empty");
+ goto PVACL_ERROR;
+ }
+ OCStackResult rst = OCGetACLResource((void*) g_ctx, dev, getAclCB);
+ if(OC_STACK_OK != rst)
+ {
+ OIC_LOG_V(ERROR, TAG, "OCGetACLResource API error: %d", rst);
+
+ goto PVACL_ERROR;
+ }
+ if(waitCallbackRet()) // input |g_doneCB| flag implicitly
+ {
+ OIC_LOG(ERROR, TAG, "OCGetACLResource callback error");
+ goto PVACL_ERROR;
+ }
+
+ // display the result of get credential
+ printf(" > Get ACL SUCCEEDED\n");
+
+ return 0;
+
+PVACL_ERROR:
+ return -1;
+}
+
static int unlinkPairwise(void)
{
// check |own_list| for unlinking pairwise devices
static int selectTwoDiffNum(int* a, int* b, const int max, const char* str)
{
- if(!a || !b || 2>=max || !str)
+ if(!a || !b || 2>max || !str)
{
return -1;
}
printf("** [E] REMOVE THE SELECTED DEVICE\n");
printf("** 50. Remove the Selected Device\n\n");
+ printf("** [F] GET SECURITY RESOURCE FOR DEBUGGING ONLY\n");
+ printf("** 60. Get the Credential resources of the Selected Device\n");
+ printf("** 61. Get the ACL resources of the Selected Device\n\n");
+
printf("** [F] EXIT PROVISIONING CLIENT\n");
printf("** 99. Exit Provisionong Client\n\n");
OIC_LOG(ERROR, TAG, "_50_REMOVE_SELEC_DEV_: error");
}
break;
+ case _60_GET_CRED_:
+ if(getCred())
+ {
+ OIC_LOG(ERROR, TAG, "_60_GET_CRED_: error");
+ }
+ break;
+ case _61_GET_ACL_:
+ if(getAcl())
+ {
+ OIC_LOG(ERROR, TAG, "_61_GET_ACL_: error");
+ }
+ break;
case _99_EXIT_PRVN_CLT_:
goto PMCLT_ERROR;
default:
const OicUuid_t *ptDeviceId, const OicUuid_t *firstDeviceId,
const OicUuid_t *secondDeviceId, OicSecCred_t **firstCred, OicSecCred_t **secondCred)
{
- if (NULL == ptDeviceId || NULL == firstDeviceId || NULL != *firstCred || \
- NULL == secondDeviceId || NULL != *secondCred)
+ if (NULL == ptDeviceId || NULL == firstDeviceId || NULL == firstCred || NULL != *firstCred || \
+ NULL == secondDeviceId || NULL == secondCred || NULL != *secondCred)
{
OIC_LOG(INFO, TAG, "Invalid params");
return OC_STACK_INVALID_PARAM;
OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
const OicUuid_t *deviceId, OicSecCred_t **const cred)
{
- if (NULL == ptDeviceId || NULL == deviceId || NULL == cred)
+ if (NULL == ptDeviceId || NULL == deviceId || NULL == cred || NULL != *cred)
{
return OC_STACK_INVALID_PARAM;
}
}
/**
+ * this function requests CRED information to resource.
+ *
+ * @param[in] ctx Application context would be returned in result callback.
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
+ request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OCProvisionResultCB resultCallback)
+{
+ return SRPGetCredResource(ctx, selectedDeviceInfo, resultCallback);
+}
+
+/**
+ * this function requests ACL information to resource.
+ *
+ * @param[in] ctx Application context would be returned in result callback.
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
+ request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OCProvisionResultCB resultCallback)
+{
+ return SRPGetACLResource(ctx, selectedDeviceInfo, resultCallback);
+}
+
+/**
* function to provision credential to devices.
*
* @param[in] ctx Application context would be returned in result callback.
&ownerKey, &ptDeviceID);
VERIFY_NON_NULL(TAG, cred, ERROR);
+ // TODO: Added as workaround. Will be replaced soon.
+ cred->privateData.encoding = OIC_ENCODING_RAW;
+
+#if 1
+ // NOTE: Test codes to use BASE64 encoded owner PSK.
+ uint32_t outSize = 0;
+ size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
+ char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
+ VERIFY_NON_NULL(TAG, b64Buf, ERROR);
+ b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
+
+ OICFree( cred->privateData.data );
+ cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
+ VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
+
+ strncpy(cred->privateData.data, b64Buf, outSize);
+ cred->privateData.data[outSize] = '\0';
+ cred->privateData.encoding = OIC_ENCODING_BASE64;
+ cred->privateData.len = outSize;
+ OICFree(b64Buf);
+#endif //End of Test codes
+
res = AddCredential(cred);
if(res != OC_STACK_OK)
{
memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
//Fill private data as empty string
- newCredential.privateData.data = NULL;
+ newCredential.privateData.data = "";
newCredential.privateData.len = 0;
+ newCredential.privateData.encoding = ownerCredential->privateData.encoding;
#ifdef __WITH_X509__
newCredential.publicData.data = NULL;
newCredential.publicData.len = 0;
#endif
-
+ int secureFlag = 0;
//Send owner credential to new device : PUT /oic/sec/cred [ owner credential ]
- if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData, &secPayload->payloadSize))
+ if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
+ &secPayload->payloadSize, secureFlag))
{
OICFree(secPayload);
OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
// Use seure port of doxm for OTM and Provision.
while (resPayload)
{
- if (0 == strncmp(resPayload->uri, OIC_RSRC_DOXM_URI, sizeof(OIC_RSRC_DOXM_URI)))
+ if (0 == strncmp(resPayload->uri, OIC_RSRC_DOXM_URI, strlen(OIC_RSRC_DOXM_URI)))
{
OIC_LOG_V(INFO,TAG,"resPaylod->uri:%s",resPayload->uri);
OIC_LOG(INFO, TAG, "Found doxm resource.");
return OC_STACK_KEEP_TRANSACTION;
}
+ res = GetDoxmDeviceID(&myId);
+ if(OC_STACK_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "Error while getting my UUID.");
+ DeleteDoxmBinData(ptrDoxm);
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+ //if this is owned discovery and this is PT's reply, discard it
+ if((pDInfo->isOwnedDiscovery) &&
+ (0 == memcmp(&ptrDoxm->deviceID.id, &myId.id, sizeof(myId.id))) )
+ {
+ OIC_LOG(DEBUG, TAG, "discarding provision tool's reply");
+ DeleteDoxmBinData(ptrDoxm);
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
clientResponse->devAddr.port,
clientResponse->devAddr.adapter,
int numOfResults; /**< Number of results in result array.**/
};
+// Structure to carry get security resource APIs data to callback.
+typedef struct GetSecData GetSecData_t;
+struct GetSecData {
+ void *ctx;
+ const OCProvisionDev_t *deviceInfo; /**< Pointer to PMDevInfo_t.**/
+ OCProvisionResultCB resultCallback; /**< Pointer to result callback.**/
+ OCProvisionResult_t *resArr; /**< Result array.**/
+ int numOfResults; /**< Number of results in result array.**/
+};
+
/**
* Structure to carry PCONF provision API data to callback.
*/
return OC_STACK_NO_MEMORY;
}
secPayload->base.type = PAYLOAD_TYPE_SECURITY;
- OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData, &secPayload->payloadSize);
+ int secureFlag = 0;
+ OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
+ &secPayload->payloadSize, secureFlag);
if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
{
OCPayloadDestroy((OCPayload *)secPayload);
return OC_STACK_NO_MEMORY;
}
secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+ int secureFlag = 0;
OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
- &secPayload->payloadSize);
+ &secPayload->payloadSize, secureFlag);
if ((OC_STACK_OK != res) || (NULL == secPayload->securityData))
{
OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
return res;
}
+
+/**
+ * Internal Function to store results in result array during GetCredResourceCB.
+ */
+static void registerResultForGetCredResourceCB(GetSecData_t *GetSecData,
+ OCStackResult stackresult)
+{
+ OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCredResourceCB "
+ "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
+ memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
+ GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
+ GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
+ ++(GetSecData->numOfResults);
+}
+
+/**
+ * Callback handler of SRPGetCredResource.
+ *
+ * @param[in] ctx ctx value passed to callback from calling function.
+ * @param[in] UNUSED handle to an invocation
+ * @param[in] clientResponse Response from queries to remote servers.
+ * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
+ * and OC_STACK_KEEP_TRANSACTION to keep it.
+ */
+static OCStackApplicationResult SRPGetCredResourceCB(void *ctx, OCDoHandle UNUSED,
+ OCClientResponse *clientResponse)
+{
+ OIC_LOG_V(INFO, TAG, "Inside SRPGetCredResourceCB.");
+ (void)UNUSED;
+ VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
+ GetSecData_t *GetSecData = (GetSecData_t*)ctx;
+ OCProvisionResultCB resultCallback = GetSecData->resultCallback;
+
+ if (clientResponse)
+ {
+ if(OC_STACK_OK == clientResponse->result)
+ {
+ uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+ size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+
+ OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
+
+ registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
+ ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+ GetSecData->resArr,
+ false);
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+ }
+ registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
+ ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+ GetSecData->resArr,
+ false);
+ OIC_LOG_V(ERROR, TAG, "SRPGetCredResourceCB received Null clientResponse");
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+
+ return OC_STACK_DELETE_TRANSACTION;
+}
+
+
+OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OCProvisionResultCB resultCallback)
+{
+ VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(TAG, resultCallback, ERROR, OC_STACK_INVALID_CALLBACK);
+
+ char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+ if(!PMGenerateQuery(true,
+ selectedDeviceInfo->endpoint.addr,
+ selectedDeviceInfo->securePort,
+ selectedDeviceInfo->connType,
+ query, sizeof(query), OIC_RSRC_CRED_URI))
+ {
+ OIC_LOG(ERROR, TAG, "SRPGetCredResource : Failed to generate query");
+ return OC_STACK_ERROR;
+ }
+ OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+ OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
+ cbData.cb = &SRPGetCredResourceCB;
+ GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
+ if (NULL == GetSecData)
+ {
+ OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+ GetSecData->deviceInfo = selectedDeviceInfo;
+ GetSecData->resultCallback = resultCallback;
+ GetSecData->numOfResults=0;
+ GetSecData->ctx = ctx;
+
+ int noOfRiCalls = 1;
+ GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
+ if (NULL == GetSecData->resArr)
+ {
+ OICFree(GetSecData);
+ OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+ cbData.context = (void *)GetSecData;
+ cbData.cd = NULL;
+ OCMethod method = OC_REST_GET;
+ OCDoHandle handle = NULL;
+ OIC_LOG(DEBUG, TAG, "Sending Get Cred to resource server");
+ OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
+ selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
+ if (OC_STACK_OK != ret)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack resource error");
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+ }
+ VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
+ OIC_LOG(DEBUG, TAG, "OUT SRPGetCredResource");
+
+ return OC_STACK_OK;
+}
+
+/**
+ * Internal Function to store results in result array during GetACLResourceCB.
+ */
+static void registerResultForGetACLResourceCB(GetSecData_t *GetSecData,
+ OCStackResult stackresult)
+{
+ OIC_LOG_V(INFO, TAG, "Inside registerResultForGetACLResourceCB "
+ "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
+ memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
+ GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
+ GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
+ ++(GetSecData->numOfResults);
+}
+
+/**
+ * Callback handler of SRPGetACLResource.
+ *
+ * @param[in] ctx ctx value passed to callback from calling function.
+ * @param[in] UNUSED handle to an invocation
+ * @param[in] clientResponse Response from queries to remote servers.
+ * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
+ * and OC_STACK_KEEP_TRANSACTION to keep it.
+ */
+static OCStackApplicationResult SRPGetACLResourceCB(void *ctx, OCDoHandle UNUSED,
+ OCClientResponse *clientResponse)
+{
+ OIC_LOG_V(INFO, TAG, "Inside SRPGetACLResourceCB.");
+ (void)UNUSED;
+ VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
+ GetSecData_t *GetSecData = (GetSecData_t*)ctx;
+ OCProvisionResultCB resultCallback = GetSecData->resultCallback;
+
+ if (clientResponse)
+ {
+ if(OC_STACK_OK == clientResponse->result)
+ {
+ uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
+ size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+
+ OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
+
+ registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
+ ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+ GetSecData->resArr,
+ false);
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+ }
+ registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
+ ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
+ GetSecData->resArr,
+ false);
+ OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+
+ return OC_STACK_DELETE_TRANSACTION;
+}
+
+
+OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OCProvisionResultCB resultCallback)
+{
+ VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR, OC_STACK_INVALID_PARAM);
+ VERIFY_NON_NULL(TAG, resultCallback, ERROR, OC_STACK_INVALID_CALLBACK);
+
+ char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+ if(!PMGenerateQuery(true,
+ selectedDeviceInfo->endpoint.addr,
+ selectedDeviceInfo->securePort,
+ selectedDeviceInfo->connType,
+ query, sizeof(query), OIC_RSRC_ACL_URI))
+ {
+ OIC_LOG(ERROR, TAG, "SRPGetACLResource : Failed to generate query");
+ return OC_STACK_ERROR;
+ }
+ OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+ OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
+ cbData.cb = &SRPGetACLResourceCB;
+ GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
+ if (NULL == GetSecData)
+ {
+ OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+ GetSecData->deviceInfo = selectedDeviceInfo;
+ GetSecData->resultCallback = resultCallback;
+ GetSecData->numOfResults=0;
+ GetSecData->ctx = ctx;
+
+ int noOfRiCalls = 1;
+ GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
+ if (NULL == GetSecData->resArr)
+ {
+ OICFree(GetSecData);
+ OIC_LOG(ERROR, TAG, "Unable to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+ cbData.context = (void *)GetSecData;
+ cbData.cd = NULL;
+ OCMethod method = OC_REST_GET;
+ OCDoHandle handle = NULL;
+ OIC_LOG(DEBUG, TAG, "Sending Get ACL to resource server");
+ OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
+ selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
+ if (OC_STACK_OK != ret)
+ {
+ OIC_LOG(ERROR, TAG, "OCStack resource error");
+ OICFree(GetSecData->resArr);
+ OICFree(GetSecData);
+ }
+ VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
+ OIC_LOG(DEBUG, TAG, "OUT SRPGetACLResource");
+
+ return OC_STACK_OK;
+}
'secureresourceprovider.cpp',
'provisioningdatabasemanager.cpp',
'ocprovisioningmanager.cpp',
+ 'credentialgeneratortest.cpp',
]
if target_os not in ['windows']:
--- /dev/null
+/* *****************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * *****************************************************************/
+#include "gtest/gtest.h"
+#include "credentialgenerator.h"
+#include "oic_malloc.h"
+
+
+TEST(PMGeneratePairWiseCredentialsTest, InvalidProvisioningtoolDevID)
+{
+ OicUuid_t *firstDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(firstDevID)
+ {
+ firstDevID->id[0] = 1;
+ }
+ OicUuid_t *SecondDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(SecondDevID)
+ {
+ SecondDevID->id[0] = 2;
+ }
+ OicSecCred_t *cred1 = NULL;
+ OicSecCred_t *cred2 = NULL;
+ size_t keySize = OWNER_PSK_LENGTH_128;
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGeneratePairWiseCredentials(NO_SECURITY_MODE,
+ keySize, NULL, firstDevID, SecondDevID, &cred1, &cred2));
+ OICFree(firstDevID);
+ OICFree(SecondDevID);
+}
+
+TEST(PMGeneratePairWiseCredentialsTest, InvalidFirstDevID)
+{
+ OicUuid_t *SecondDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(SecondDevID)
+ {
+ SecondDevID->id[0] = 2;
+ }
+ OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(provisioningDevID)
+ {
+ provisioningDevID->id[0] = 1;
+ }
+ OicSecCred_t *cred1 = NULL;
+ OicSecCred_t *cred2 = NULL;
+ size_t keySize = OWNER_PSK_LENGTH_128;
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGeneratePairWiseCredentials(NO_SECURITY_MODE,
+ keySize, provisioningDevID, NULL, SecondDevID, &cred1, &cred2));
+ OICFree(SecondDevID);
+ OICFree(provisioningDevID);
+}
+
+TEST(PMGeneratePairWiseCredentialsTest, InvalidSecondDevID)
+{
+ OicUuid_t *firstDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(firstDevID)
+ {
+ firstDevID->id[0] = 1;
+ }
+ OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(provisioningDevID)
+ {
+ provisioningDevID->id[0] = 2;
+ }
+ OicSecCred_t *cred1 = NULL;
+ OicSecCred_t *cred2 = NULL;
+ size_t keySize = OWNER_PSK_LENGTH_128;
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGeneratePairWiseCredentials(NO_SECURITY_MODE, keySize,
+ provisioningDevID, firstDevID, NULL, &cred1, &cred2));
+ OICFree(firstDevID);
+ OICFree(provisioningDevID);
+}
+
+TEST(PMGeneratePairWiseCredentialsTest, InvalidCred)
+{
+ OicUuid_t *firstDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(firstDevID)
+ {
+ firstDevID->id[0] = 1;
+ }
+ OicUuid_t *SecondDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(SecondDevID)
+ {
+ SecondDevID->id[0] = 2;
+ }
+ OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(provisioningDevID)
+ {
+ provisioningDevID->id[0] = 3;
+ }
+ size_t keySize = OWNER_PSK_LENGTH_128;
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGeneratePairWiseCredentials(NO_SECURITY_MODE, keySize,
+ provisioningDevID, firstDevID, SecondDevID, NULL, NULL));
+ OICFree(firstDevID);
+ OICFree(SecondDevID);
+ OICFree(provisioningDevID);
+}
+
+#ifdef __WITH_X509__
+
+TEST(PMGenerateCertificateCredentialsTest, InvalidProvisioningtoolDevID)
+{
+ OicUuid_t *DevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(DevID)
+ {
+ DevID->id[0] = 1;
+ }
+ OicSecCred_t *cred = NULL;
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(NULL, DevID, &cred));
+ OICFree(DevID);
+}
+
+TEST(PMGenerateCertificateCredentialsTest, InvalidDevID)
+{
+ OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(provisioningDevID)
+ {
+ provisioningDevID->id[0] = 1;
+ }
+ OicSecCred_t *cred = NULL;
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(provisioningDevID,
+ NULL, &cred));
+ OICFree(provisioningDevID);
+}
+
+TEST(PMGenerateCertificateCredentialsTest, InvalidCred)
+{
+ OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(provisioningDevID)
+ {
+ provisioningDevID->id[0] = 1;
+ }
+ OicUuid_t *DevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+ if(DevID)
+ {
+ DevID->id[0] = 1;
+ }
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(provisioningDevID, DevID,
+ NULL));
+ OICFree(provisioningDevID);
+ OICFree(DevID);
+}
+
+#endif // __WITH_X509__
+
(void) UNUSED4;
}
+static OCStackResult OTMLoadSecretCallback(OTMContext_t* otmCtx)
+{
+ //dummy callback
+ (void) otmCtx;
+ return OC_STACK_OK;
+}
+
+TEST(OCInitPMTest, NullPath)
+{
+ EXPECT_EQ(OC_STACK_OK, OCInitPM(NULL));
+}
+
TEST(OCProvisionPairwiseDevicesTest, NullDevice1)
{
pDev1.doxm = &defaultDoxm1;
size_t noOfDevices = 0;
EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetLinkedStatus(NULL, &list, &noOfDevices));
}
+
+TEST(OCDeleteUuidListTest, NullUuidList)
+{
+ OCDeleteUuidList(NULL);
+ EXPECT_EQ(1, 1);
+}
+
+TEST(OCDeleteACLListTest, NullACLList)
+{
+ OCDeleteACLList(NULL);
+ EXPECT_EQ(1, 1);
+}
+
+TEST(OCDeletePdAclListTest, NullPdACLList)
+{
+ OCDeletePdAclList(NULL);
+ EXPECT_EQ(1, 1);
+}
+
+TEST(OCDeleteDiscoveredDevicesTest, NullProvisionDevList)
+{
+ OCDeleteDiscoveredDevices(NULL);
+ EXPECT_EQ(1, 1);
+}
+
+TEST(OCSetOwnerTransferCallbackDataTest, NULLCallback)
+{
+ OicSecOxm_t ownershipTransferMethod = OIC_JUST_WORKS;
+ EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCSetOwnerTransferCallbackData(ownershipTransferMethod,
+ NULL));
+}
+
+TEST(OCSetOwnerTransferCallbackDataTest, InvalidOXMType)
+{
+ OicSecOxm_t ownershipTransferMethod = OIC_OXM_COUNT;
+ OTMCallbackData_t stOTMCallbackData = { &OTMLoadSecretCallback, NULL, NULL, NULL};
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSetOwnerTransferCallbackData(ownershipTransferMethod,
+ &stOTMCallbackData));
+}
char cwd[1024] = {0};
char svr_db_path[1024] = {0};
GetCurrentWorkingDirectory(cwd, sizeof(cwd));
- sprintf(svr_db_path, "%s%s", cwd, SVR_DB_PATH);
+ snprintf(svr_db_path, sizeof(svr_db_path), "%s%s", cwd, SVR_DB_PATH);
return fopen(svr_db_path, mode);
}
//Delete previous PDB, if exist.
GetCurrentWorkingDirectory(cwd, sizeof(cwd));
- sprintf(del_cmd, "rm -rf %stest.db", cwd);
+ snprintf(del_cmd, sizeof(del_cmd), "rm -rf %stest.db", cwd);
system(del_cmd);
//Delete previous SVR DB, if exist.
- sprintf(del_cmd, "rm -rf %s%s", cwd, SVR_DB_PATH);
+ snprintf(del_cmd, sizeof(del_cmd), "rm -rf %s%s", cwd, SVR_DB_PATH);
system(del_cmd);
//Generate default SVR DB.
- sprintf(svrdb_path, "%s%s", cwd, SVR_DB_PATH);
+ snprintf(svrdb_path, sizeof(svrdb_path), "%s%s", cwd, SVR_DB_PATH);
fp = fopen(svrdb_path, "w");
if(NULL != fp)
{
size_t numberItems = fwrite(DEFAULT_SVR_DB, 1, sizeof(DEFAULT_SVR_DB), fp);
- ASSERT_TRUE(sizeof(DEFAULT_SVR_DB) == numberItems);
fclose(fp);
+ ASSERT_TRUE(sizeof(DEFAULT_SVR_DB) == numberItems);
}
//Execute sample server to perform ownership transfer
int status2 = 0;
if(0 == (g_myPID1 = fork()))
{
- sprintf(server1_path, "%ssample_server1", cwd);
+ snprintf(server1_path, sizeof(server1_path), "%ssample_server1", cwd);
status1 = system(server1_path);
(void)status1;
}
if(0 == (g_myPID2 = fork()))
{
- sprintf(server2_path, "%ssample_server2", cwd);
+ snprintf(server2_path, sizeof(server2_path), "%ssample_server2", cwd);
status2= system(server2_path);
(void)status2;
}
//initialize Provisioning DB Manager
- sprintf(pdb_path, "%stest.db", cwd);
+ snprintf(pdb_path, sizeof(pdb_path), "%stest.db", cwd);
result = OCInitPM(pdb_path);
EXPECT_EQ(OC_STACK_OK, result);
tempDev = tempDev->next;
}
- EXPECT_EQ(2/*Server*/ + 1/*PT*/, NumOfOwnDevice);
+ EXPECT_EQ(2/*Server*/ , NumOfOwnDevice);
}
TEST(PerformLinkDevices, NullParam)
char cwd[1024] = {0};
char cred_path[1024] = {0};
GetCurrentWorkingDirectory(cwd, sizeof(cwd));
- sprintf(cred_path, "%s%s", cwd, CRED_FILE);
+ snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
return fopen(cred_path, mode);
}
char del_cmd[1024] = {0};
FILE* fp = NULL;
GetCurrentWorkingDirectory(cwd, sizeof(cwd));
- sprintf(del_cmd, "rm -rf %s%s", cwd, CRED_FILE);
+ snprintf(del_cmd, sizeof(del_cmd), "rm -rf %s%s", cwd, CRED_FILE);
system(del_cmd);
//Generate default SVR DB.
- sprintf(cred_path, "%s%s", cwd, CRED_FILE);
+ snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
fp = fopen(cred_path, "w");
if(NULL != fp)
{
char cwd[1024] = {0};
char cred_path[1024] = {0};
GetCurrentWorkingDirectory(cwd, sizeof(cwd));
- sprintf(cred_path, "%s%s", cwd, CRED_FILE);
+ snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
return fopen(cred_path, mode);
}
char del_cmd[1024] = {0};
FILE* fp = NULL;
GetCurrentWorkingDirectory(cwd, sizeof(cwd));
- sprintf(del_cmd, "rm -rf %s%s", cwd, CRED_FILE);
+ snprintf(del_cmd, sizeof(del_cmd), "rm -rf %s%s", cwd, CRED_FILE);
system(del_cmd);
//Generate default SVR DB.
- sprintf(cred_path, "%s%s", cwd, CRED_FILE);
+ snprintf(cred_path, sizeof(cred_path), "%s%s", cwd, CRED_FILE);
fp = fopen(cred_path, "w");
if(NULL != fp)
{
char* tagName = NULL;
size_t len = 0;
CborType type = cbor_value_get_type(&aclMap);
- if (type == CborTextStringType)
+ if (type == CborTextStringType && cbor_value_is_text_string(&aclMap))
{
cborFindResult = cbor_value_dup_text_string(&aclMap, &tagName, &len, NULL);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
char* acName = NULL;
size_t acLen = 0;
CborType acType = cbor_value_get_type(&aclistMap);
- if (acType == CborTextStringType)
+ if (acType == CborTextStringType && cbor_value_is_text_string(&aclistMap))
{
cborFindResult = cbor_value_dup_text_string(&aclistMap, &acName, &acLen, NULL);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACLIST Map.");
char* name = NULL;
size_t len = 0;
CborType type = cbor_value_get_type(&aclMap);
- if (type == CborTextStringType)
+ if (type == CborTextStringType && cbor_value_is_text_string(&aclMap))
{
cborFindResult = cbor_value_dup_text_string(&aclMap, &name, &len, NULL);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
if (name)
{
// Subject -- Mandatory
- if (strcmp(name, OIC_JSON_SUBJECTID_NAME) == 0)
+ if (strcmp(name, OIC_JSON_SUBJECTID_NAME) == 0 && cbor_value_is_text_string(&aclMap))
{
char *subject = NULL;
cborFindResult = cbor_value_dup_text_string(&aclMap, &subject, &len, NULL);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
- while(cbor_value_is_valid(&rMap))
+ while(cbor_value_is_valid(&rMap) && cbor_value_is_text_string(&rMap))
{
char *rMapName = NULL;
size_t rMapNameLen = 0;
// Permissions -- Mandatory
if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
{
- cborFindResult = cbor_value_get_uint64(&aclMap, (uint64_t *) &acl->permission);
+ uint64_t tmp64;
+
+ cborFindResult = cbor_value_get_uint64(&aclMap, &tmp64);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a PERM Value.");
+ acl->permission = tmp64;
}
// Period -- Not mandatory
- if (strcmp(name, OIC_JSON_PERIOD_NAME) == 0)
+ if (strcmp(name, OIC_JSON_PERIOD_NAME) == 0 && cbor_value_is_array(&aclMap))
{
CborValue period = { .parser = NULL };
cborFindResult = cbor_value_get_array_length(&aclMap, &acl->prdRecrLen);
acl->periods = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
VERIFY_NON_NULL(TAG, acl->periods, ERROR);
int i = 0;
- while (cbor_value_is_text_string(&period))
+ while (cbor_value_is_text_string(&period) && cbor_value_is_text_string(&period))
{
cborFindResult = cbor_value_dup_text_string(&period, &acl->periods[i++],
&len, NULL);
acl->recurrences = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
int i = 0;
- while (cbor_value_is_text_string(&recurrences))
+ while (cbor_value_is_text_string(&recurrences) && cbor_value_is_text_string(&recurrences))
{
cborFindResult = cbor_value_dup_text_string(&recurrences,
&acl->recurrences[i++], &len, NULL);
}
// TODO : Need to modify headAcl->owners[0].id to headAcl->rowner based on RAML spec.
- if (strcmp(tagName, OIC_JSON_ROWNERID_NAME) == 0)
+ if (strcmp(tagName, OIC_JSON_ROWNERID_NAME) == 0 && cbor_value_is_text_string(&aclMap))
{
char *stRowner = NULL;
cborFindResult = cbor_value_dup_text_string(&aclMap, &stRowner, &len, NULL);
size_t size = 0;
OCEntityHandlerResult ehRet;
- // Process the REST querystring parameters
- if (ehRequest->query)
+ OicUuid_t subject = {.id= { 0 } };
+
+ // In case, 'subject' field is included in REST request.
+ if (ehRequest->query && GetSubjectFromQueryString(ehRequest->query, &subject))
{
+ OIC_LOG(DEBUG,TAG,"'subject' field is inculded in REST request.");
OIC_LOG(DEBUG, TAG, "HandleACLGetRequest processing query");
- OicUuid_t subject = {.id= { 0 } };
char resource[MAX_URI_LENGTH] = { 0 };
OicSecAcl_t *savePtr = NULL;
const OicSecAcl_t *currentAce = NULL;
// 'Subject' field is MUST for processing a querystring in REST request.
- VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
-
GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
/*
}
}
}
+ // In case, 'subject' field is not included in REST request.
else
{
+ OIC_LOG(DEBUG,TAG,"'subject' field is not inculded in REST request.");
// Convert ACL data into CBOR format for transmission.
if (OC_STACK_OK != AclToCBORPayload(gAcl, &payload, &size))
{
ret = OCCreateResource(&gAclHandle,
OIC_RSRC_TYPE_SEC_ACL,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_ACL_URI,
ACLEntityHandler,
NULL,
}
}
-static size_t OicSecAmaclCount(const OicSecAmacl_t *secAmacl)
-{
- size_t size = 0;
- for (const OicSecAmacl_t *amacl = secAmacl; amacl; amacl = amacl->next)
- {
- size++;
- }
- return size;
-}
-
OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amaclS, uint8_t **cborPayload,
size_t *cborSize)
{
cborFindResult = cbor_value_enter_container(&amaclCbor, &amaclMap);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Amacl Map.");
- while(cbor_value_is_valid(&amaclMap))
+ while(cbor_value_is_valid(&amaclMap) && cbor_value_is_text_string(&amaclMap))
{
char *name = NULL;
size_t len = 0;
cborFindResult = cbor_value_enter_container(&amaclMap, &rsrcMap);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
- while(cbor_value_is_valid(&rsrcMap))
+ while(cbor_value_is_valid(&rsrcMap) && cbor_value_is_text_string(&rsrcMap))
{
// resource name
char *rsrcName = NULL;
cborFindResult = cbor_value_enter_container(&rsrcArray, &rMap);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Rlist Map");
- while(cbor_value_is_valid(&rMap))
+ while(cbor_value_is_valid(&rMap) && cbor_value_is_text_string(&rMap))
{
char *rMapName = NULL;
size_t rMapNameLen = 0;
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering AMS Array Container.");
headAmacl->amss = (OicUuid_t *)OICCalloc(headAmacl->amssLen, sizeof(*headAmacl->amss));
VERIFY_NON_NULL(TAG, headAmacl->amss, ERROR);
- while (cbor_value_is_valid(&amsArray))
+ while (cbor_value_is_valid(&amsArray) && cbor_value_is_text_string(&amsArray))
{
char *amssId = NULL;
cborFindResult = cbor_value_dup_text_string(&amsArray, &amssId, &len, NULL);
}
// Rowner -- Mandatory
- if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name))
+ if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name) && cbor_value_is_text_string(&amaclMap))
{
char *stRowner = NULL;
cborFindResult = cbor_value_dup_text_string(&amaclMap, &stRowner, &len, NULL);
{
OCStackResult ret = OCCreateResource(&gAmaclHandle,
OIC_RSRC_TYPE_SEC_AMACL,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_AMACL_URI,
AmaclEntityHandler,
NULL,
{
OCStackResult ret = OC_STACK_ERROR;
const char GET_ACE_QUERY_FMT[] = "%s?%s=%s;%s=%s";
- char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {0};
- uint32_t outLen = 0;
char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
OCCallbackData cbData = {.context=NULL};
OCDevAddr destAddr = {.adapter = OC_ADAPTER_IP};
- B64Result b64Ret;
char *subID = NULL;
VERIFY_NON_NULL(TAG, context, ERROR);
}
OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
- size_t *cborSize)
+ size_t *cborSize, int secureFlag)
{
if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
{
mapSize++;
}
#endif /* __WITH_X509__ */
- if (cred->privateData.data)
+ if (!secureFlag && cred->privateData.data)
{
mapSize++;
}
}
#endif /*__WITH_X509__*/
//PrivateData -- Not Mandatory
- if(cred->privateData.data)
+ if(!secureFlag && cred->privateData.data)
{
CborEncoder privateMap;
const size_t privateMapSize = 2;
cborEncoderResult = cbor_encoder_create_map(&credMap, &privateMap, privateMapSize);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PrivateData Map");
- cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_DATA_NAME,
- strlen(OIC_JSON_DATA_NAME));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Tag.");
- cborEncoderResult = cbor_encode_byte_string(&privateMap, cred->privateData.data,
- cred->privateData.len);
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Value.");
-
// TODO: Need to data strucure modification for OicSecKey_t.
- cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_ENCODING_NAME,
- strlen(OIC_JSON_ENCODING_NAME));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Tag.");
- cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_SEC_ENCODING_RAW,
- strlen(OIC_SEC_ENCODING_RAW));
- VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Value.");
+ // TODO: Added as workaround, will be replaced soon.
+ if(OIC_ENCODING_RAW == cred->privateData.encoding)
+ {
+ cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_ENCODING_NAME,
+ strlen(OIC_JSON_ENCODING_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Tag.");
+ cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_SEC_ENCODING_RAW,
+ strlen(OIC_SEC_ENCODING_RAW));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Value.");
+
+ cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_DATA_NAME,
+ strlen(OIC_JSON_DATA_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Tag.");
+ cborEncoderResult = cbor_encode_byte_string(&privateMap, cred->privateData.data,
+ cred->privateData.len);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Value.");
+ }
+ else if(OIC_ENCODING_BASE64 == cred->privateData.encoding)
+ {
+ cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_ENCODING_NAME,
+ strlen(OIC_JSON_ENCODING_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Tag.");
+ cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_SEC_ENCODING_BASE64,
+ strlen(OIC_SEC_ENCODING_BASE64));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Value.");
+
+ cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_DATA_NAME,
+ strlen(OIC_JSON_DATA_NAME));
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Tag.");
+ cborEncoderResult = cbor_encode_text_string(&privateMap, (char*)(cred->privateData.data),
+ cred->privateData.len);
+ VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Value.");
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Unknow encoding type for private data.");
+ VERIFY_CBOR_SUCCESS(TAG, CborErrorUnknownType, "Failed Adding Private Encoding Value.");
+ }
cborEncoderResult = cbor_encoder_close_container(&credMap, &privateMap);
VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing PrivateData Map.");
// Since the allocated initial memory failed, double the memory.
cborLen += encoder.ptr - encoder.end;
cborEncoderResult = CborNoError;
- ret = CredToCBORPayload(credS, cborPayload, &cborLen);
+ ret = CredToCBORPayload(credS, cborPayload, &cborLen, secureFlag);
*cborSize = cborLen;
}
char* tagName = NULL;
size_t len = 0;
CborType type = cbor_value_get_type(&CredRootMap);
- if (type == CborTextStringType)
+ if (type == CborTextStringType && cbor_value_is_text_string(&CredRootMap))
{
cborFindResult = cbor_value_dup_text_string(&CredRootMap, &tagName, &len, NULL);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in CRED Root Map.");
VERIFY_NON_NULL(TAG, cred, ERROR);
- while(cbor_value_is_valid(&credMap))
+ while(cbor_value_is_valid(&credMap) && cbor_value_is_text_string(&credMap))
{
char* name = NULL;
CborType type = cbor_value_get_type(&credMap);
//credid
if (strcmp(name, OIC_JSON_CREDID_NAME) == 0)
{
- cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credId);
+ uint64_t credId = 0;
+ cborFindResult = cbor_value_get_uint64(&credMap, &credId);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredId.");
+ cred->credId = (uint16_t)credId;
}
// subjectid
if (strcmp(name, OIC_JSON_SUBJECTID_NAME) == 0)
// credtype
if (strcmp(name, OIC_JSON_CREDTYPE_NAME) == 0)
{
- cborFindResult = cbor_value_get_uint64(&credMap, (uint64_t *) &cred->credType);
+ uint64_t credType = 0;
+ cborFindResult = cbor_value_get_uint64(&credMap, &credType);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredType.");
+ cred->credType = (OicSecCredType_t)credType;
}
// privatedata
if (strcmp(name, OIC_JSON_PRIVATEDATA_NAME) == 0)
{
char* privname = NULL;
CborType type = cbor_value_get_type(&privateMap);
- if (type == CborTextStringType)
+ if (type == CborTextStringType && cbor_value_is_text_string(&privateMap))
{
cborFindResult = cbor_value_dup_text_string(&privateMap, &privname,
&len, NULL);
// PrivateData::privdata -- Mandatory
if (strcmp(privname, OIC_JSON_DATA_NAME) == 0)
{
- cborFindResult = cbor_value_dup_byte_string(&privateMap, &cred->privateData.data,
- &cred->privateData.len, NULL);
+ if(cbor_value_is_byte_string(&privateMap))
+ {
+ cborFindResult = cbor_value_dup_byte_string(&privateMap, &cred->privateData.data,
+ &cred->privateData.len, NULL);
+ }
+ else if(cbor_value_is_text_string(&privateMap))
+ {
+ cborFindResult = cbor_value_dup_text_string(&privateMap, (char**)(&cred->privateData.data),
+ &cred->privateData.len, NULL);
+ }
+ else
+ {
+ cborFindResult = CborErrorUnknownType;
+ OIC_LOG(ERROR, TAG, "Unknow type for private data.");
+ }
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PrivateData.");
}
+
// PrivateData::encoding -- Mandatory
if (strcmp(privname, OIC_JSON_ENCODING_NAME) == 0)
{
- // TODO: Need to update data structure, just ignore encoding value now.
+ // TODO: Added as workaround. Will be replaced soon.
+ char* strEncoding = NULL;
+ cborFindResult = cbor_value_dup_text_string(&privateMap, &strEncoding, &len, NULL);
+ VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding EncodingType");
+
+ if(strcmp(strEncoding, OIC_SEC_ENCODING_RAW) == 0)
+ {
+ cred->privateData.encoding = OIC_ENCODING_RAW;
+ }
+ else if(strcmp(strEncoding, OIC_SEC_ENCODING_BASE64) == 0)
+ {
+ cred->privateData.encoding = OIC_ENCODING_BASE64;
+ }
+ else
+ {
+ //For unit test
+ cred->privateData.encoding = OIC_ENCODING_RAW;
+ OIC_LOG(WARNING, TAG, "Unknow encoding type dectected for private data.");
+ }
+
+ OICFree(strEncoding);
}
}
if (cbor_value_is_valid(&privateMap))
{
char* pubname = NULL;
CborType type = cbor_value_get_type(&pubMap);
- if (type == CborTextStringType)
+ if (type == CborTextStringType && cbor_value_is_text_string(&pubMap))
{
cborFindResult = cbor_value_dup_text_string(&pubMap, &pubname,
&len, NULL);
if (pubname)
{
// PrivateData::privdata -- Mandatory
- if (strcmp(pubname, OIC_JSON_DATA_NAME) == 0)
+ if (strcmp(pubname, OIC_JSON_DATA_NAME) == 0 && cbor_value_is_byte_string(&pubMap))
{
cborFindResult = cbor_value_dup_byte_string(&pubMap, &cred->publicData.data,
&cred->publicData.len, NULL);
}
//ROwner -- Mandatory
- if (strcmp(tagName, OIC_JSON_ROWNERID_NAME) == 0)
+ if (strcmp(tagName, OIC_JSON_ROWNERID_NAME) == 0 && cbor_value_is_text_string(&CredRootMap))
{
char *stRowner = NULL;
cborFindResult = cbor_value_dup_text_string(&CredRootMap, &stRowner, &len, NULL);
VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
memcpy(cred->privateData.data, privateData->data, privateData->len);
cred->privateData.len = privateData->len;
+
+ // TODO: Added as workaround. Will be replaced soon.
+ cred->privateData.encoding = OIC_ENCODING_RAW;
+
+#if 0
+ // NOTE: Test codes to use base64 for credential.
+ uint32_t outSize = 0;
+ size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((privateData->len + 1));
+ char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
+ VERIFY_NON_NULL(TAG, b64Buf, ERROR);
+ b64Encode(privateData->data, privateData->len, b64Buf, b64BufSize, &outSize);
+
+ OICFree( cred->privateData.data );
+ cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
+ VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
+
+ strcpy(cred->privateData.data, b64Buf);
+ cred->privateData.encoding = OIC_ENCODING_BASE64;
+ cred->privateData.len = outSize;
+ OICFree(b64Buf);
+#endif //End of Test codes
+
}
VERIFY_NON_NULL(TAG, rownerID, ERROR);
{
uint8_t *payload = NULL;
size_t size = 0;
- OCStackResult res = CredToCBORPayload(cred, &payload, &size);
+ int secureFlag = 0;
+ OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
if ((OC_STACK_OK == res) && payload)
{
if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);
//Generate owner credential based on recevied credential information
- receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
- VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
- receviedCred->privateData.len = OWNER_PSK_LENGTH_128;
- memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
+
+ // TODO: Added as workaround, will be replaced soon.
+ if(OIC_ENCODING_RAW == receviedCred->privateData.encoding)
+ {
+ receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
+ VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
+ receviedCred->privateData.len = OWNER_PSK_LENGTH_128;
+ memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
+ }
+ else if(OIC_ENCODING_BASE64 == receviedCred->privateData.encoding)
+ {
+ uint32_t b64OutSize = 0;
+ size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
+ char* b64Buf = OICCalloc(1, b64BufSize);
+ VERIFY_NON_NULL(TAG, b64Buf, ERROR);
+
+ b64Encode(ownerPSK, OWNER_PSK_LENGTH_128, b64Buf, b64BufSize, &b64OutSize);
+
+ receviedCred->privateData.data = (uint8_t *)OICCalloc(1, b64OutSize + 1);
+ VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
+ receviedCred->privateData.len = b64OutSize;
+ strncpy((char*)receviedCred->privateData.data, b64Buf, b64OutSize);
+ receviedCred->privateData.data[b64OutSize] = '\0';
+ }
+ else
+ {
+ // TODO: error
+ VERIFY_SUCCESS(TAG, OIC_ENCODING_UNKNOW, ERROR);
+ }
OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");
OicSecCred_t *cred = NULL;
uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData);
size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
+
OCStackResult res = CBORPayloadToCred(payload, size, &cred);
if (res == OC_STACK_OK)
{
return ret;
}
+/**
+ * The entity handler determines how to process a GET request.
+ */
+static OCEntityHandlerResult HandleGetRequest (const OCEntityHandlerRequest * ehRequest)
+{
+ OIC_LOG(INFO, TAG, "HandleGetRequest processing GET request");
+
+ // Convert Cred data into CBOR for transmission
+ size_t size = 0;
+ uint8_t *payload = NULL;
+ int secureFlag = 1;
+
+ const OicSecCred_t *cred = gCred;
+ OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
+
+ // A device should always have a default cred. Therefore, payload should never be NULL.
+ OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+
+ // Send response payload to request originator
+ if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size))
+ {
+ ehRet = OC_EH_ERROR;
+ OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandlePstatGetRequest");
+ }
+ OICFree(payload);
+ return ehRet;
+}
+
static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
{
OCEntityHandlerResult ret = OC_EH_ERROR;
switch (ehRequest->method)
{
case OC_REST_GET:
- ret = OC_EH_FORBIDDEN;
+ ret = HandleGetRequest(ehRequest);;
break;
case OC_REST_PUT:
ret = HandlePutRequest(ehRequest);
{
OCStackResult ret = OCCreateResource(&gCredHandle,
OIC_RSRC_TYPE_SEC_CRED,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_CRED_URI,
CredEntityHandler,
NULL,
- OC_RES_PROP_NONE);
+ OC_SECURE);
if (OC_STACK_OK != ret)
{
if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
{
OIC_LOG (INFO, TAG, "Credentials are expired.");
- ret = -1;
return ret;
}
}
// Copy PSK.
- result_length = cred->privateData.len;
- memcpy(result, cred->privateData.data, result_length);
- return result_length;
+ // TODO: Added as workaround. Will be replaced soon.
+ if(OIC_ENCODING_RAW == cred->privateData.encoding)
+ {
+ result_length = cred->privateData.len;
+ memcpy(result, cred->privateData.data, result_length);
+ }
+ else if(OIC_ENCODING_BASE64 == cred->privateData.encoding)
+ {
+ size_t outBufSize = B64DECODE_OUT_SAFESIZE((cred->privateData.len + 1));
+ uint8_t* outKey = OICCalloc(1, outBufSize);
+ uint32_t outKeySize;
+ if(NULL == outKey)
+ {
+ OIC_LOG (ERROR, TAG, "Failed to memoray allocation.");
+ return ret;
+ }
+
+ if(B64_OK == b64Decode((char*)cred->privateData.data, cred->privateData.len, outKey, outBufSize, &outKeySize))
+ {
+ memcpy(result, outKey, outKeySize);
+ ret = outKeySize;
+ }
+ else
+ {
+ OIC_LOG (ERROR, TAG, "Failed to base64 decoding.");
+ }
+
+ OICFree(outKey);
+ }
+
+ return ret;
}
}
}
default:
{
OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
- ret = -1;
}
break;
}
}
uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
- OicSecKey_t privKey = {privData, OWNER_PSK_LENGTH_128};
+ OicSecKey_t privKey = {privData, OWNER_PSK_LENGTH_128, OIC_ENCODING_RAW};
OicSecCred_t* cred = NULL;
int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, rownerID->id,
UUID_LENGTH, PBKDF_ITERATIONS,
OCStackResult ret = OC_STACK_ERROR;
uint8_t *cborPayload = NULL;
size_t size = 0;
+ int secureFlag = 0;
OicUuid_t prevId = {.id={0}};
if(NULL == newROwner)
memcpy(prevId.id, gCred->rownerID.id, sizeof(prevId.id));
memcpy(gCred->rownerID.id, newROwner->id, sizeof(newROwner->id));
- ret = CredToCBORPayload(gCred, &cborPayload, &size);
+ ret = CredToCBORPayload(gCred, &cborPayload, &size, secureFlag);
VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
ret = UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, cborPayload, size);
{
OCStackResult ret = OCCreateResource(&gCrlHandle,
OIC_RSRC_TYPE_SEC_CRL,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_CRL_URI,
CRLEntityHandler,
NULL,
int i = 0;
size_t len = 0;
- while (cbor_value_is_valid(&oxmType))
+ while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
{
cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
&len, NULL);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
int i = 0;
- while (cbor_value_is_valid(&oxm))
+ while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
{
cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
{
OCStackResult ret = OCCreateResource(&gDoxmHandle,
OIC_RSRC_TYPE_SEC_DOXM,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_DOXM_URI,
DoxmEntityHandler,
NULL,
- OC_OBSERVABLE | OC_SECURE |
+ OC_SECURE |
OC_DISCOVERABLE);
if (OC_STACK_OK != ret)
dpair = (OicSecDpairing_t *)OICCalloc(1, sizeof(*dpair));
VERIFY_NON_NULL(TAG, dpair, ERROR);
- while (cbor_value_is_valid(&dpairMap))
+ while (cbor_value_is_valid(&dpairMap) && cbor_value_is_text_string(&dpairMap))
{
char *name = NULL;
size_t len = 0;
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a value in DPair map");
type = cbor_value_get_type(&dpairMap);
- if (0 == strcmp(OIC_JSON_SPM_NAME, name))
+ if (0 == strcmp(OIC_JSON_SPM_NAME, name) && cbor_value_is_integer(&dpairMap))
{
cborFindResult = cbor_value_get_int(&dpairMap, (int *) &dpair->spm);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SPM Value");
ret = OCCreateResource(&gDpairHandle,
OIC_RSRC_TYPE_SEC_DPAIRING,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_DPAIRING_URI,
DpairingEntityHandler,
NULL,
char *name = NULL;
size_t len = 0;
CborType type = cbor_value_get_type(&pconfMap);
- if (type == CborTextStringType)
+ if (type == CborTextStringType && cbor_value_is_text_string(&pconfMap))
{
cborFindResult = cbor_value_dup_text_string(&pconfMap, &name, &len, NULL);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
if (name)
{
//EDP -- Mandatory
- if(0 == strcmp(OIC_JSON_EDP_NAME, name))
+ if(0 == strcmp(OIC_JSON_EDP_NAME, name) && cbor_value_is_boolean(&pconfMap))
{
cborFindResult = cbor_value_get_boolean(&pconfMap, &pconf->edp);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
cborFindResult = cbor_value_enter_container(&pconfMap, &prm);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to eneter array");
- while (cbor_value_is_valid(&prm))
+ while (cbor_value_is_valid(&prm) && cbor_value_is_integer(&prm))
{
cborFindResult = cbor_value_get_int(&prm, (int *)&pconf->prm[i++]);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
}
}
//PIN -- Mandatory
- if (0 == strcmp(OIC_JSON_PIN_NAME, name))
+ if (0 == strcmp(OIC_JSON_PIN_NAME, name) && cbor_value_is_byte_string(&pconfMap))
{
uint8_t *pin = NULL;
cborFindResult = cbor_value_dup_byte_string(&pconfMap, &pin, &len, NULL);
char* name = NULL;
size_t len = 0;
CborType type = cbor_value_get_type(&pdAclMap);
- if (type == CborTextStringType)
+ if (type == CborTextStringType && cbor_value_is_text_string(&pdAclMap))
{
cborFindResult = cbor_value_dup_text_string(&pdAclMap, &name,
&len, NULL);
if (name)
{
// Resources -- Mandatory
- if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
+ if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0 && cbor_value_is_array(&pdAclMap))
{
int i = 0;
CborValue resources = { .parser = NULL };
cborFindResult = cbor_value_enter_container(&resources, &rMap);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
- while(cbor_value_is_valid(&rMap))
+ while(cbor_value_is_valid(&rMap) && cbor_value_is_text_string(&rMap))
{
char *rMapName = NULL;
size_t rMapNameLen = 0;
}
// Permissions -- Mandatory
- if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
+ if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0 && cbor_value_is_unsigned_integer(&pdAclMap))
{
- cborFindResult = cbor_value_get_uint64(&pdAclMap,
- (uint64_t *) &pdacl->permission);
+ uint64_t permission = 0;
+ cborFindResult = cbor_value_get_uint64(&pdAclMap, &permission);
+ pdacl->permission = (uint16_t)permission;
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");
}
// Period -- Not mandatory
- if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0)
+ if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0 && cbor_value_is_array(&pdAclMap))
{
int i = 0;
CborValue period = { .parser = NULL };
pdacl->periods = (char **) OICCalloc(pdacl->prdRecrLen, sizeof(char*));
VERIFY_NON_NULL(TAG, pdacl->periods, ERROR);
- while (cbor_value_is_text_string(&period))
+ while (cbor_value_is_text_string(&period) && cbor_value_is_text_string(&period))
{
cborFindResult = cbor_value_dup_text_string(&period,
&pdacl->periods[i++], &len, NULL);
}
// Recurrence -- Not mandatory
- if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
+ if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0 && cbor_value_is_array(&pdAclMap))
{
int i = 0;
CborValue recurrences = { .parser = NULL };
pdacl->recurrences = (char **) OICCalloc(pdacl->prdRecrLen, sizeof(char*));
VERIFY_NON_NULL(TAG, pdacl->recurrences, ERROR);
- while (cbor_value_is_text_string(&recurrences))
+ while (cbor_value_is_text_string(&recurrences) && cbor_value_is_text_string(&recurrences))
{
cborFindResult = cbor_value_dup_text_string(&recurrences,
&pdacl->recurrences[i++], &len, NULL);
}
//PDDev -- Mandatory
- if (strcmp(name, OIC_JSON_PDDEV_LIST_NAME) == 0)
+ if (strcmp(name, OIC_JSON_PDDEV_LIST_NAME) == 0 && cbor_value_is_array(&pconfMap))
{
int i = 0;
CborValue pddevs = { .parser = NULL };
pconf->pddevs = (OicUuid_t *)OICMalloc(pconf->pddevLen * sizeof(OicUuid_t));
VERIFY_NON_NULL(TAG, pconf->pddevs, ERROR);
- while (cbor_value_is_valid(&pddevs))
+ while (cbor_value_is_valid(&pddevs) && cbor_value_is_text_string(&pddevs))
{
char *pddev = NULL;
cborFindResult = cbor_value_dup_text_string(&pddevs, &pddev, &len, NULL);
}
//Mandatory - Device Id
- if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name))
+ if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name) && cbor_value_is_text_string(&pconfMap))
{
char *deviceId = NULL;
cborFindResult = cbor_value_dup_text_string(&pconfMap, &deviceId, &len, NULL);
}
// ROwner -- Mandatory
- if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name))
+ if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name) && cbor_value_is_text_string(&pconfMap))
{
char *rowner = NULL;
cborFindResult = cbor_value_dup_text_string(&pconfMap, &rowner, &len, NULL);
ret = OCCreateResource(&gPconfHandle,
OIC_RSRC_TYPE_SEC_PCONF,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_PCONF_URI,
PconfEntityHandler,
NULL,
{
OCStackResult ret = OCCreateResource(&gPstatHandle,
OIC_RSRC_TYPE_SEC_PSTAT,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_PSTAT_URI,
PstatEntityHandler,
NULL,
- OC_RES_PROP_NONE);
+ OC_SECURE |
+ OC_DISCOVERABLE);
if (OC_STACK_OK != ret)
{
const char * SVR_DB_FILE_NAME = "oic_svr_db.json";
const char * SVR_DB_DAT_FILE_NAME = "oic_svr_db.dat";
-const char * OIC_MI_DEF = "oic.mi.def";
//AMACL
-const char * OIC_RSRC_TYPE_SEC_AMACL = "oic.sec.amacl";
+const char * OIC_RSRC_TYPE_SEC_AMACL = "oic.r.amacl";
const char * OIC_RSRC_AMACL_URI = "/oic/sec/amacl";
const char * OIC_JSON_AMACL_NAME = "amacl";
//ACL
-const char * OIC_RSRC_TYPE_SEC_ACL = "oic.sec.acl";
+const char * OIC_RSRC_TYPE_SEC_ACL = "oic.r.acl";
const char * OIC_RSRC_ACL_URI = "/oic/sec/acl";
const char * OIC_JSON_ACL_NAME = "acl";
const char * OIC_JSON_ACLIST_NAME = "aclist";
const char * OIC_JSON_ACES_NAME = "aces";
//Pstat
-const char * OIC_RSRC_TYPE_SEC_PSTAT = "oic.sec.pstat";
+const char * OIC_RSRC_TYPE_SEC_PSTAT = "oic.r.pstat";
const char * OIC_RSRC_PSTAT_URI = "/oic/sec/pstat";
const char * OIC_JSON_PSTAT_NAME = "pstat";
//doxm
-const char * OIC_RSRC_TYPE_SEC_DOXM = "oic.sec.doxm";
+const char * OIC_RSRC_TYPE_SEC_DOXM = "oic.r.doxm";
const char * OIC_RSRC_DOXM_URI = "/oic/sec/doxm";
const char * OIC_JSON_DOXM_NAME = "doxm";
//cred
-const char * OIC_RSRC_TYPE_SEC_CRED = "oic.sec.cred";
+const char * OIC_RSRC_TYPE_SEC_CRED = "oic.r.cred";
const char * OIC_RSRC_CRED_URI = "/oic/sec/cred";
const char * OIC_JSON_CRED_NAME = "cred";
const char * OIC_JSON_CREDS_NAME = "creds";
//CRL
-const char * OIC_RSRC_TYPE_SEC_CRL = "oic.sec.crl";
+const char * OIC_RSRC_TYPE_SEC_CRL = "oic.r.crl";
const char * OIC_RSRC_CRL_URI = "/oic/sec/crl";
const char * OIC_JSON_CRL_NAME = "crl";
//SACL
-const char * OIC_RSRC_TYPE_SEC_SACL = "oic.sec.sacl";
+const char * OIC_RSRC_TYPE_SEC_SACL = "oic.r.sacl";
const char * OIC_RSRC_SACL_URI = "/oic/sec/sacl";
const char * OIC_JSON_SACL_NAME = "sacl";
//svc
-const char * OIC_RSRC_TYPE_SEC_SVC = "oic.sec.svc";
+const char * OIC_RSRC_TYPE_SEC_SVC = "oic.r.svc";
const char * OIC_RSRC_SVC_URI = "/oic/sec/svc";
const char * OIC_JSON_SVC_NAME = "svc";
//pconf
-const char * OIC_RSRC_TYPE_SEC_PCONF = "oic.sec.pconf";
+const char * OIC_RSRC_TYPE_SEC_PCONF = "oic.r.pconf";
const char * OIC_RSRC_PCONF_URI = "/oic/sec/pconf";
const char * OIC_JSON_PCONF_NAME = "pconf";
//dpairing
-const char * OIC_RSRC_TYPE_SEC_DPAIRING = "oic.sec.dpairing";
+const char * OIC_RSRC_TYPE_SEC_DPAIRING = "oic.r.dpairing";
const char * OIC_RSRC_DPAIRING_URI = "/oic/sec/dpairing";
const char * OIC_JSON_DPAIRING_NAME = "dpairing";
//version
-const char * OIC_RSRC_TYPE_SEC_VER = "oic.sec.ver";
+const char * OIC_RSRC_TYPE_SEC_VER = "oic.r.ver";
const char * OIC_RSRC_VER_URI = "/oic/sec/ver";
const char * OIC_JSON_VER_NAME = "ver";
type = cbor_value_get_type(&svcMap);
// Service Device Identity
- if (0 == strcmp(OIC_JSON_SERVICE_DEVICE_ID, name))
+ if (0 == strcmp(OIC_JSON_SERVICE_DEVICE_ID, name) && cbor_value_is_byte_string(&svcMap))
{
uint8_t *subjectId = NULL;
cborFindResult = cbor_value_dup_byte_string(&svcMap, &subjectId, &len, NULL);
OICFree(subjectId);
}
// Service Type
- if (0 == strcmp(OIC_JSON_SERVICE_TYPE, name))
+ if (0 == strcmp(OIC_JSON_SERVICE_TYPE, name) && cbor_value_is_integer(&svcMap))
{
cborFindResult = cbor_value_get_int(&svcMap, (int *) &svc->svct);
VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find SVCT.");
}
// Owners -- Mandatory
- if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
+ if (0 == strcmp(OIC_JSON_OWNERS_NAME, name) && cbor_value_is_array(&svcMap))
{
int i = 0;
CborValue owners = { .parser = NULL };
svc->owners = (OicUuid_t *)OICCalloc(svc->ownersLen, sizeof(*svc->owners));
VERIFY_NON_NULL(TAG, svc->owners, ERROR);
- while (cbor_value_is_valid(&owners))
+ while (cbor_value_is_valid(&owners) && cbor_value_is_byte_string(&owners))
{
uint8_t *owner = NULL;
cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
{
OCStackResult ret = OCCreateResource(&gSvcHandle,
OIC_RSRC_TYPE_SEC_SVC,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_SVC_URI,
SVCEntityHandler,
NULL,
{
OCStackResult ret = OCCreateResource(&gVerHandle,
OIC_RSRC_TYPE_SEC_VER,
- OIC_MI_DEF,
+ OC_RSRVD_INTERFACE_DEFAULT,
OIC_RSRC_VER_URI,
VerEntityHandler,
NULL,
value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
//printf("CRED json : \n%s\n", cJSON_PrintUnformatted(value));
size_t credCborSize = 0;
+ int secureFlag = 0;
if (NULL != value)
{
OicSecCred_t *cred = JSONToCredBin(jsonStr);
VERIFY_NON_NULL(TAG, cred, FATAL);
- ret = CredToCBORPayload(cred, &credCbor, &credCborSize);
+ ret = CredToCBORPayload(cred, &credCbor, &credCborSize, secureFlag);
if(OC_STACK_OK != ret)
{
OIC_LOG (ERROR, TAG, "Failed converting Cred to Cbor Payload");
# Build flags
######################################################################
srmtest_env.PrependUnique(CPPPATH = [
- '../../ocmalloc/include',
+ '../../../c_common/oic_malloc/include',
'../../connectivity/inc',
'../../connectivity/api',
'../../connectivity/external/inc',
'../../connectivity/lib/libcoap-4.1.1',
- '../include',
'../include/internal',
'../../logger/include',
- '../../ocmalloc/include',
'../../stack/include',
'../../stack/include/internal',
'../../../oc_logger/include',
'../../../../extlibs/gtest/gtest-1.7.0/include',
'../../../../extlibs/cjson/',
- '../provisioning/include',
-# '../../../../extlibs/tinydtls/',
+ '../provisioning/include',
'../include'
])
#endif
cred->credType = SYMMETRIC_PAIR_WISE_KEY;
+ cred->privateData.encoding = OIC_ENCODING_RAW;
cred->privateData.data = (uint8_t *)OICCalloc(1, strlen("My private Key11") + 1);
VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
OICStrcpy((char *)cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
cred->next->roleIdsLen = 0;
#endif
cred->next->credType = SYMMETRIC_PAIR_WISE_KEY;
+ cred->next->privateData.encoding = OIC_ENCODING_RAW;
sz = strlen("My private Key21") + 1;
cred->next->privateData.data = (uint8_t *)OICCalloc(1, sz);
VERIFY_NON_NULL(TAG, cred->next->privateData.data, ERROR);
OIC_LOG_V(INFO, TAG, "cred->publicData.data = %s", credTmp1->publicData.data);
}
#endif /* __WITH_X509__ */
- OIC_LOG_V(INFO, TAG, "cred->rownerID = %s", credTmp1->rownerID.id);
+ OIC_LOG_V(INFO, TAG, "cred->rownerID = %s", credTmp1->rownerID.id);
}
}
ASSERT_TRUE(NULL != cred);
uint8_t *payload = NULL;
size_t size = 0;
- EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
+ int secureFlag = 0;
+ EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size, secureFlag));
if (!payload)
{
DeleteCredList(cred);
TEST(CredResourceTest, CredToCBORPayloadNULL)
{
+ int secureFlag = 0;
OicSecCred_t *cred = getCredList();
- EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, NULL, 0));
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, NULL, 0, secureFlag));
size_t size = 0;
uint8_t *cborPayload = (uint8_t *) OICCalloc(1, 10);
if (!cborPayload)
DeleteCredList(cred);
}
ASSERT_TRUE(NULL != cborPayload);
- EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, &size));
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, &size, secureFlag));
OICFree(cborPayload);
cborPayload = NULL;
- EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, &cborPayload, &size));
- EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, 0));
- EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, NULL, &size));
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, &cborPayload, &size,secureFlag));
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, 0, secureFlag));
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, NULL, &size, secureFlag));
DeleteCredList(cred);
}
{
uint8_t* payload = NULL;
size_t size = 0;
+ int secureFlag = 0;
OicSecCred_t *cred = getCredList();
- EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
+ EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size, secureFlag));
if (!payload)
{
DeleteCredList(cred);
uint8_t *payload = NULL;
size_t size = 0;
- EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size));
+ int secureFlag = 0;
+ EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size, secureFlag));
DeleteCredList(cred1);
ASSERT_TRUE(NULL != payload);
DeleteCredList(cred2);
}
+TEST(CredResourceTest, CBORPayloadToCredSecureVALID)
+{
+ OicSecCred_t *cred1 = getCredList();
+ ASSERT_TRUE(NULL != cred1);
+ cred1->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
+ ASSERT_TRUE(NULL != cred1->privateData.data);
+ cred1->privateData.len = OWNER_PSK_LENGTH_128;
+
+ uint8_t *payload = NULL;
+ size_t size = 0;
+ int secureFlag = 1;
+ EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size, secureFlag));
+
+ ASSERT_TRUE(NULL != payload);
+
+ OicSecCred_t *cred2 = NULL;
+ EXPECT_EQ(OC_STACK_OK, CBORPayloadToCred(payload, size, &cred2));
+ ASSERT_TRUE(cred2 != NULL);
+ ASSERT_TRUE(NULL == cred2->privateData.data);
+ ASSERT_TRUE(0 == cred2->privateData.len);
+
+ OICFree(payload);
+
+ DeleteCredList(cred1);
+ DeleteCredList(cred2);
+}
+
TEST(CredResourceTest, CBORPayloadToCredNULL)
{
OicSecCred_t *cred = NULL;
}
#endif
+#if defined(__WITH_DTLS__)
+TEST(CredGetDtlsPskCredentialsTest, NullResult)
+{
+ EXPECT_EQ(-1, GetDtlsPskCredentials(CA_DTLS_PSK_KEY, NULL, 0, NULL, 0));
+}
+
+TEST(CredAddTmpPskWithPINTest, NullSubject)
+{
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, AddTmpPskWithPIN(NULL, SYMMETRIC_PAIR_WISE_KEY,
+ NULL, 0, NULL, NULL));
+}
+#endif
+TEST(CredCBORPayloadToCredTest, NullPayload)
+{
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, NULL));
+}
uint8_t numVendorOptions,
OCHeaderOption * vendorOptions,
OCObserveAction observeAction,
- OCObservationId observeID);
+ OCObservationId observeID,
+ uint16_t messageID);
/**
* Find a server request in the server request list and delete
/** The coap scheme */
#define OC_COAP_SCHEME "coap://"
-/** the first outgoing sequence number will be 5*/
-#define OC_OFFSET_SEQUENCE_NUMBER (4)
+/** the first outgoing sequence number will be 2*/
+#define OC_OFFSET_SEQUENCE_NUMBER (1)
/**
* This structure will be created in occoap and passed up the stack on the server side.
OC_EXPORT bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType);
OC_EXPORT bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* iface);
+OC_EXPORT bool OCRepPayloadAddModelVersion(OCRepPayload* payload, const char* dmv);
OC_EXPORT bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType);
OC_EXPORT bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* iface);
OC_EXPORT OCStringLL* CloneOCStringLL (OCStringLL* ll);
OC_EXPORT void OCFreeOCStringLL(OCStringLL* ll);
+/**
+ * This function creates a list from a string (with separated contents if several)
+ * @param text single string or CSV text fields
+ * @return newly allocated linked list
+ * @note separator is ',' (according to rfc4180, ';' is not valid)
+ **/
+OC_EXPORT OCStringLL* OCCreateOCStringLL(const char* text);
+
+/**
+ * This function creates a string from a list (with separated contents if several)
+ * @param ll Pointer to list
+ * @return newly allocated string
+ * @note separator is ',' (according to rfc4180)
+ **/
+OC_EXPORT char* OCCreateString(const OCStringLL* ll);
+
#ifdef __cplusplus
}
#endif
{
OC_EH_OK = 0,
OC_EH_ERROR,
- OC_EH_RESOURCE_CREATED,
- OC_EH_RESOURCE_DELETED,
- OC_EH_SLOW,
- OC_EH_FORBIDDEN,
- OC_EH_RESOURCE_NOT_FOUND
+ OC_EH_RESOURCE_CREATED, // 2.01
+ OC_EH_RESOURCE_DELETED, // 2.02
+ OC_EH_SLOW, // 2.05
+ OC_EH_FORBIDDEN, // 4.03
+ OC_EH_RESOURCE_NOT_FOUND, // 4.04
+ OC_EH_VALID, // 2.03
+ OC_EH_CHANGED, // 2.04
+ OC_EH_CONTENT, // 2.05
+ OC_EH_BAD_REQ, // 4.00
+ OC_EH_UNAUTHORIZED_REQ, // 4.01
+ OC_EH_BAD_OPT, // 4.02
+ OC_EH_METHOD_NOT_ALLOWED, // 4.05
+ OC_EH_NOT_ACCEPTABLE, // 4.06
+ OC_EH_INTERNAL_SERVER_ERROR, // 5.00
+ OC_EH_RETRANSMIT_TIMEOUT // 5.04
} OCEntityHandlerResult;
/**
OCStringLL *types;
/** Pointer to the device specification version.*/
char *specVersion;
- /** Pointer to the device data model version.*/
- char *dataModleVersion;
+ /** Pointer to the device data model versions (in CSV format).*/
+ OCStringLL *dataModelVersions;
} OCDeviceInfo;
#ifdef RA_ADAPTER
char *uri;
/** Resource Type */
- char *type;
+ OCStringLL *type;
/** Interface */
OCStringLL *iface;
char *sid;
char* deviceName;
char* specVersion;
- char* dataModelVersion;
+ OCStringLL *dataModelVersions;
OCStringLL *interfaces;
OCStringLL *types;
} OCDevicePayload;
/** Pointer to the array of the received vendor specific header options.*/
OCHeaderOption * rcvdVendorSpecificHeaderOptions;
+ /** Message id.*/
+ uint16_t messageID;
+
/** the payload from the request PDU.*/
OCPayload *payload;
}
if (payload->type)
{
- OIC_LOG_V(level, PL_TAG, "\tResource Type: %s", payload->type);
+ for (OCStringLL *strll = payload->type; strll; strll = strll->next)
+ {
+ OIC_LOG_V(level, PL_TAG, "\tResource Type: %s", strll->value);
+ }
}
OIC_LOG(level, PL_TAG, "\tInterface:");
for (OCStringLL *itf = payload->iface; itf; itf = itf->next)
OIC_LOG_V(level, PL_TAG, "\tSID:%s", payload->sid);
OIC_LOG_V(level, PL_TAG, "\tDevice Name:%s", payload->deviceName);
OIC_LOG_V(level, PL_TAG, "\tSpec Version:%s", payload->specVersion);
- OIC_LOG_V(level, PL_TAG, "\tData Model Version:%s", payload->dataModelVersion);
+ if (payload->dataModelVersions)
+ {
+ OIC_LOG(level, PL_TAG, "\tData Model Version:");
+ for (OCStringLL *strll = payload->dataModelVersions; strll; strll = strll->next)
+ {
+ OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
+ }
+ }
if (payload->types)
{
OIC_LOG(level, PL_TAG, "\tResource Type:");
#include <pthread.h>
#endif
#include <array>
+#include "oic_malloc.h"
#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
const char *version = "myVersion";
const char *systemTime = "2015-05-15T11.04";
const char *specVersion = "myDeviceSpecVersion";
-const char* dataModleVersion = "myDeviceModleVersion";
+const char *dataModelVersions = "myDeviceModelVersions";
// Entity handler should check for resourceTypeName and ResourceInterface in order to GET
// the existence of a known resource
{
free (deviceInfo.deviceName);
free (deviceInfo.specVersion);
- free (deviceInfo.dataModleVersion);
+ OCFreeOCStringLL (deviceInfo.dataModelVersions);
}
bool DuplicateString(char** targetString, const char* sourceString)
return OC_STACK_ERROR;
}
-OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, const char* dataModleVersion)
+OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, const char* dataModelVersions)
{
if(!DuplicateString(&deviceInfo.deviceName, deviceName))
{
{
return OC_STACK_ERROR;
}
- if(!DuplicateString(&deviceInfo.dataModleVersion, dataModleVersion))
+ OCFreeOCStringLL(deviceInfo.dataModelVersions);
+ deviceInfo.dataModelVersions = OCCreateOCStringLL(dataModelVersions);
+ if (!deviceInfo.dataModelVersions)
{
return OC_STACK_ERROR;
}
exit (EXIT_FAILURE);
}
- registrationResult = SetDeviceInfo(deviceName, specVersion, dataModleVersion);
+ registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
if (registrationResult != OC_STACK_OK)
{
static char CRED_FILE_DEVOWNER[] = "oic_svr_db_client_devowner.dat";
static char CRED_FILE_NONDEVOWNER[] = "oic_svr_db_client_nondevowner.dat";
const char * OIC_RSRC_DOXM_URI = "/oic/sec/doxm";
+const char * OIC_RSRC_PSTAT_URI = "/oic/sec/pstat";
int gQuitFlag = 0;
OIC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
OIC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
- OIC_LOG(INFO, TAG, "-d 0 : Client as Device Owner");
- OIC_LOG(INFO, TAG, "-d 1 : Client as Non Device Owner");
+ OIC_LOG(INFO, TAG, "-d 0 : Client as Non Device Owner");
+ OIC_LOG(INFO, TAG, "-d 1 : Client as Device Owner");
}
OCStackResult InvokeOCDoResource(std::ostringstream &query,
res = res->next;
continue;
}
+ if (0 == strcmp(coapServerResource.c_str(),OIC_RSRC_PSTAT_URI))
+ {
+ OIC_LOG(INFO,TAG,"Skip: pstat is secure virtual resource");
+ res = res->next;
+ continue;
+ }
if (res->secure)
{
OIC_LOG_V(INFO,TAG,"SECUREPORT: %d",res->port);
#include <signal.h>
#include <pthread.h>
#include <array>
+#include "oic_malloc.h"
#include "ocstack.h"
#include "logger.h"
#include "ocpayload.h"
const char *version = "myVersion";
const char *systemTime = "2015-05-15T11.04";
const char *specVersion = "myDeviceSpecVersion";
-const char* dataModleVersion = "myDeviceModleVersion";
+const char *dataModelVersions = "myDeviceModelVersions";
// Entity handler should check for resourceTypeName and ResourceInterface in order to GET
// the existence of a known resource
{
free (deviceInfo.deviceName);
free (deviceInfo.specVersion);
- free (deviceInfo.dataModleVersion);
+ OCFreeOCStringLL (deviceInfo.dataModelVersions);
}
bool DuplicateString(char** targetString, const char* sourceString)
return OC_STACK_ERROR;
}
-OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, const char* dataModleVersion)
+OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, const char* dataModelVersions)
{
if(!DuplicateString(&deviceInfo.deviceName, deviceName))
{
{
return OC_STACK_ERROR;
}
- if(!DuplicateString(&deviceInfo.dataModleVersion, dataModleVersion))
+ OCFreeOCStringLL(deviceInfo.dataModelVersions);
+ deviceInfo.dataModelVersions = OCCreateOCStringLL(dataModelVersions);
+ if (!deviceInfo.dataModelVersions)
{
return OC_STACK_ERROR;
}
exit (EXIT_FAILURE);
}
- registrationResult = SetDeviceInfo(deviceName, specVersion, dataModleVersion);
+ registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
if (registrationResult != OC_STACK_OK)
{
cp resource/csdk/stack/include/ocpresence.h %{DEST_INC_DIR}
cp resource/csdk/stack/include/ocpayload.h %{DEST_INC_DIR}
cp resource/c_common/platform_features.h %{DEST_INC_DIR}
+cp resource/c_common/*/include/*.h %{DEST_INC_DIR}
cp resource/csdk/stack/include/payload_logging.h %{DEST_INC_DIR}
cp resource/csdk/stack/include/rdpayload.h %{DEST_INC_DIR}
cp extlibs/tinycbor/tinycbor/src/cbor.h %{DEST_INC_DIR}
request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
OC_OBSERVE_NO_OPTION,
- 0);
+ 0,
+ request->coapID);
if (result == OC_STACK_OK)
{
ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
return OC_STACK_RESOURCE_ERROR;
}
- if (!resUri || !token || !*token)
+ if (!resUri || !token)
{
return OC_STACK_INVALID_PARAM;
}
{
ResourceObserver *out = NULL;
- if (token && *token)
+ if (token)
{
OIC_LOG(INFO, TAG, "Looking for token");
OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength);
OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
{
- if (!token || !*token)
+ if (!token)
{
return OC_STACK_INVALID_PARAM;
}
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+// Required for strok_r
+#define _POSIX_C_SOURCE 200112L
+#include <stdio.h>
#include "ocpayload.h"
#include "octypes.h"
#include <string.h>
#include "rdpayload.h"
#define TAG "OIC_RI_PAYLOAD"
+#define CSV_SEPARATOR ','
static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val);
return headOfClone;
}
+OCStringLL* OCCreateOCStringLL(const char* text)
+{
+ char *token = NULL;
+ char *head = NULL;
+ char *tail = NULL;
+ char *backup = NULL;
+ OCStringLL* result = NULL;
+ OCStringLL* iter = NULL;
+ OCStringLL* prev = NULL;
+ static const char delim[] = { CSV_SEPARATOR, '\0' };
+
+ VERIFY_PARAM_NON_NULL(TAG, text, "Invalid parameter");
+ backup = OICStrdup(text);
+ VERIFY_PARAM_NON_NULL(TAG, backup, "Failed allocating memory");
+
+ for (head = backup; ; head = NULL)
+ {
+ token = (char *) strtok_r(head, delim, &tail);
+ if (!token) break;
+ iter = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
+ VERIFY_PARAM_NON_NULL(TAG, iter, "Failed allocating memory");
+ if (!result)
+ {
+ result = iter;
+ }
+ else
+ {
+ prev->next = iter;
+ }
+ iter->value = OICStrdup(token);
+ VERIFY_PARAM_NON_NULL(TAG, iter->value, "Failed allocating memory");
+ prev = iter;
+ iter = iter->next;
+ }
+ OICFree(backup);
+ return result;
+
+exit:
+ OICFree(backup);
+ OCFreeOCStringLL(result);
+ return NULL;
+}
+
+char* OCCreateString(const OCStringLL* ll)
+{
+ char *str = NULL;
+ char *pos = NULL;
+ size_t len = 0;
+ size_t sublen = 0;
+ int count = 0;
+
+ if (!ll) return NULL;
+
+ for (const OCStringLL *it = ll; it ; it = it->next )
+ {
+ len += strlen(it->value) + 1;
+ }
+ str = (char*) malloc(len + 1);
+ if (!str)
+ return NULL;
+
+ pos = str;
+ for (const OCStringLL *it = ll; it ; it = it->next )
+ {
+ sublen = strlen(it->value) + 1;
+ count = snprintf(pos, len + 1, "%s%c", it->value, CSV_SEPARATOR);
+ if (count<sublen)
+ {
+ free(str);
+ return NULL;
+ }
+ len-=sublen;
+ pos+=count;
+ }
+
+ return str;
+}
+
OCRepPayload* OCRepPayloadClone (const OCRepPayload* payload)
{
if (!payload)
OICFree(payload->sid);
OICFree(payload->baseURI);
OICFree(payload->uri);
- OICFree(payload->type);
+ OCFreeOCStringLL(payload->type);
OICFree(payload->name);
OCFreeOCStringLL(payload->iface);
OCDiscoveryResourceDestroy(payload->resources);
goto exit;
}
- payload->dataModelVersion = OICStrdup(dmVer);
- if (dmVer && !payload->dataModelVersion)
+ payload->dataModelVersions = OCCreateOCStringLL(dmVer);
+ if (!payload->dataModelVersions || (dmVer && !payload->dataModelVersions->value))
{
goto exit;
}
OICFree(payload->sid);
OICFree(payload->deviceName);
OICFree(payload->specVersion);
- OICFree(payload->dataModelVersion);
+ OCFreeOCStringLL(payload->dataModelVersions);
OCFreeOCStringLL(payload->types);
OCFreeOCStringLL(payload->interfaces);
OICFree(payload);
// Discovery Links Map Length.
#define LINKS_MAP_LEN 4
+// Default data model versions in CVS form
+#define DEFAULT_DATA_MODEL_VERSIONS "res.1.1.0,sh.1.1.0"
+
// Functions all return either a CborError, or a negative version of the OC_STACK return values
static int64_t OCConvertPayloadHelper(OCPayload *payload, uint8_t *outPayload, size_t *size);
static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *outPayload,
[ // rootArray
{ // rootMap
"di" : UUID, // device ID
- "rt": "oic.wk.res"
+ "rt": ["oic.wk.res"]
"n":"MyDevice"
"if":"oic.if.ll oic.if.baseline"
"di": "0685B960-736F-46F7-BEC0-9E6CBD61ADC1",
VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting device id");
// Insert Resource Type
- err |= ConditionalAddTextStringToMap(&rootMap, OC_RSRVD_RESOURCE_TYPE,
- sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, payload->type);
+ err |= OCStringLLJoin(&rootMap, OC_RSRVD_RESOURCE_TYPE, payload->type);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting RT");
// Insert interfaces
err |= cbor_encode_uint(&policyMap, resource->bitmap);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding bitmap value to policy map");
- if (resource->secure)
- {
- err |= cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
- sizeof(OC_RSRVD_SECURE) - 1);
- VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure tag to policy map");
- err |= cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
- VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure value to policy map");
- }
- if ((resource->secure && resource->port != 0) || payload->baseURI)
+ // Secure
+ err |= cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
+ sizeof(OC_RSRVD_SECURE) - 1);
+ VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure tag to policy map");
+ err |= cbor_encode_boolean(&policyMap, resource->secure);
+ VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding secure value to policy map");
+
+ if (resource->secure || payload->baseURI)
{
err |= cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
sizeof(OC_RSRVD_HOSTING_PORT) - 1);
}
int64_t err = CborNoError;
CborEncoder encoder;
+ char *dataModelVersions = 0;
cbor_encoder_init(&encoder, outPayload, *size, 0);
CborEncoder repMap;
sizeof(OC_RSRVD_SPEC_VERSION) - 1, payload->specVersion);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding data spec version");
- // Device data Model Version
+ // Device data Model Versions
+ if (payload->dataModelVersions)
+ {
+ OIC_LOG(INFO, TAG, "Payload has data model versions");
+ dataModelVersions = OCCreateString(payload->dataModelVersions);
+ }
+ else
+ {
+ dataModelVersions = OICStrdup(DEFAULT_DATA_MODEL_VERSIONS);
+ }
err |= ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
- sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1, payload->dataModelVersion);
- VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding data model version");
+ sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1, dataModelVersions);
+ OICFree(dataModelVersions);
+ VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding data model versions");
err |= cbor_encoder_close_container(&encoder, &repMap);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed closing device map");
err = cbor_value_map_find_value(&rootMap, OC_RSRVD_RESOURCE_TYPE, &curVal);
if (cbor_value_is_valid(&curVal))
{
- err = cbor_value_dup_text_string(&curVal, &(out->type), &len, NULL);
+ err = OCParseStringLL(&rootMap, OC_RSRVD_RESOURCE_TYPE, &out->type);
VERIFY_CBOR_SUCCESS(TAG, err, "to find base uri value");
}
err = cbor_value_dup_text_string(&curVal, &out->specVersion, &len, NULL);
VERIFY_CBOR_SUCCESS(TAG, err, "to find spec version in device payload");
}
- // Data Model Version
+ // Data Model Versions
err = cbor_value_map_find_value(rootValue, OC_RSRVD_DATA_MODEL_VERSION, &curVal);
- VERIFY_CBOR_SUCCESS(TAG, err, "to find data model ver tag");
+ VERIFY_CBOR_SUCCESS(TAG, err, "to find data model versions tag");
if (cbor_value_is_valid(&curVal))
{
- err = cbor_value_dup_text_string(&curVal, &out->dataModelVersion, &len, NULL);
- VERIFY_CBOR_SUCCESS(TAG, err, "to find data model version in device payload");
+ size_t len = 0;
+ char * str = NULL;
+ err = cbor_value_dup_text_string(&curVal, &str, &len, NULL);
+ VERIFY_CBOR_SUCCESS(TAG, err, "to find data model versions in device payload");
+ out->dataModelVersions = OCCreateOCStringLL(str);
+ OICFree(str);
}
err = cbor_value_advance(rootValue);
VERIFY_CBOR_SUCCESS(TAG, err, "to advance device payload");
if (cbor_value_is_map(rootValue))
{
CborValue curVal;
+ uint64_t temp = 0;
// Sequence Number
CborError err = cbor_value_map_find_value(rootValue, OC_RSRVD_NONCE, &curVal);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding nonce tag");
- err = cbor_value_get_uint64(&curVal, (uint64_t *)&payload->sequenceNumber);
+ err = cbor_value_get_uint64(&curVal, &temp);
+ payload->sequenceNumber = (uint32_t)temp;
VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding nonce value");
// Max Age
err = cbor_value_map_find_value(rootValue, OC_RSRVD_TTL, &curVal);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding ttl tag");
- err = cbor_value_get_uint64(&curVal, (uint64_t *)&payload->maxAge);
+ temp = 0;
+ err = cbor_value_get_uint64(&curVal, &temp);
+ payload->maxAge = (uint32_t)temp;
VERIFY_CBOR_SUCCESS(TAG, err, "Failed finding ttl value");
// Trigger
for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
{
bool result = false;
- if (resource->resourceProperties & OC_EXPLICIT_DISCOVERABLE)
- {
- if (resourceTypeQuery && resourceMatchesRTFilter(resource, resourceTypeQuery))
- {
- result = true;
- }
- }
if (resource->resourceProperties & OC_DISCOVERABLE)
{
result = true;
}
else
{
- if ((interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL))) ||
- !interfaceQuery)
+ if (interfaceQuery && (0 != strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
{
discPayload->uri = OICStrdup(OC_RSRVD_WELL_KNOWN_URI);
VERIFY_NON_NULL(discPayload->uri, ERROR, OC_STACK_NO_MEMORY);
discPayload->name = OICStrdup(savedDeviceInfo.deviceName);
VERIFY_NON_NULL(discPayload->name, ERROR, OC_STACK_NO_MEMORY);
}
- discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
+ discPayload->type = (OCStringLL*)OICCalloc(1, sizeof(OCStringLL));
VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
+ discPayload->type->value = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
+ VERIFY_NON_NULL(discPayload->type->value, ERROR, OC_STACK_NO_MEMORY);
OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
}
else
{
- payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
- savedDeviceInfo.types, savedDeviceInfo.specVersion, savedDeviceInfo.dataModleVersion);
- if (!payload)
+ char *dataModelVersions = OCCreateString(savedDeviceInfo.dataModelVersions);
+ if (!dataModelVersions)
{
discoveryResult = OC_STACK_NO_MEMORY;
}
else
{
- discoveryResult = OC_STACK_OK;
+ payload = (OCPayload*) OCDevicePayloadCreate(deviceId, savedDeviceInfo.deviceName,
+ savedDeviceInfo.types, savedDeviceInfo.specVersion, dataModelVersions);
+ if (!payload)
+ {
+ discoveryResult = OC_STACK_NO_MEMORY;
+ }
+ else
+ {
+ discoveryResult = OC_STACK_OK;
+ }
+ OICFree(dataModelVersions);
}
}
}
request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
(OCObserveAction)request->observationOption,
- (OCObservationId)0);
+ (OCObservationId)0,
+ request->coapID);
VERIFY_SUCCESS(result, OC_STACK_OK);
// At this point we know for sure that defaultDeviceHandler exists
request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
(OCObserveAction)request->observationOption,
- 0);
+ 0,
+ request->coapID);
VERIFY_SUCCESS(result, OC_STACK_OK);
if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION)
request->numRcvdVendorSpecificHeaderOptions,
request->rcvdVendorSpecificHeaderOptions,
(OCObserveAction)request->observationOption,
- (OCObservationId)0);
+ (OCObservationId)0,
+ request->coapID);
if(result == OC_STACK_OK)
{
result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
OICFree(savedDeviceInfo.deviceName);
OCFreeOCStringLL(savedDeviceInfo.types);
OICFree(savedDeviceInfo.specVersion);
- OICFree(savedDeviceInfo.dataModleVersion);
+ OCFreeOCStringLL(savedDeviceInfo.dataModelVersions);
savedDeviceInfo.deviceName = NULL;
savedDeviceInfo.specVersion = NULL;
- savedDeviceInfo.dataModleVersion = NULL;
+ savedDeviceInfo.dataModelVersions = NULL;
}
static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
}
}
- if (info.dataModleVersion)
+ if (info.dataModelVersions)
{
- savedDeviceInfo.dataModleVersion = OICStrdup(info.dataModleVersion);
- if(!savedDeviceInfo.dataModleVersion && info.dataModleVersion)
+ savedDeviceInfo.dataModelVersions = CloneOCStringLL(info.dataModelVersions);
+ if(!savedDeviceInfo.dataModelVersions && info.dataModelVersions)
{
DeleteDeviceInfo();
return OC_STACK_NO_MEMORY;
}
else
{
- savedDeviceInfo.dataModleVersion = OICStrdup(OC_DATA_MODEL_VERSION);
- if(!savedDeviceInfo.dataModleVersion && OC_DATA_MODEL_VERSION)
+ savedDeviceInfo.dataModelVersions = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
+ if (!savedDeviceInfo.dataModelVersions)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ savedDeviceInfo.dataModelVersions->value = OICStrdup(OC_DATA_MODEL_VERSION);
+ if(!savedDeviceInfo.dataModelVersions->value && OC_DATA_MODEL_VERSION)
{
DeleteDeviceInfo();
return OC_STACK_NO_MEMORY;
uint8_t numVendorOptions,
OCHeaderOption * vendorOptions,
OCObserveAction observeAction,
- OCObservationId observeID)
+ OCObservationId observeID,
+ uint16_t messageID)
{
if (entityHandlerRequest)
{
entityHandlerRequest->query = queryBuf;
entityHandlerRequest->obsInfo.action = observeAction;
entityHandlerRequest->obsInfo.obsId = observeID;
+ entityHandlerRequest->messageID = messageID;
if(payload && payloadSize)
{
CAResponseResult_t ConvertEHResultToCAResult (OCEntityHandlerResult result, OCMethod method)
{
- CAResponseResult_t caResult;
+ CAResponseResult_t caResult = CA_BAD_REQ;
switch (result)
{
- case OC_EH_OK:
- switch (method)
- {
- case OC_REST_PUT:
- case OC_REST_POST:
- // This Response Code is like HTTP 204 "No Content" but only used in
- // response to POST and PUT requests.
- caResult = CA_CHANGED;
- break;
- case OC_REST_GET:
- // This Response Code is like HTTP 200 "OK" but only used in response to
- // GET requests.
- caResult = CA_CONTENT;
- break;
- default:
- // This should not happen but,
- // give it a value just in case but output an error
- caResult = CA_CONTENT;
- OIC_LOG_V(ERROR, TAG, "Unexpected OC_EH_OK return code for method [%d].", method);
- }
+ // Successful Client Request
+ case OC_EH_RESOURCE_CREATED: // 2.01
+ if (method == OC_REST_POST || method == OC_REST_PUT)
+ {
+ caResult = CA_CREATED;
+ }
break;
- case OC_EH_ERROR:
- caResult = CA_BAD_REQ;
+ case OC_EH_RESOURCE_DELETED: // 2.02
+ if (method == OC_REST_POST || method == OC_REST_DELETE)
+ {
+ caResult = CA_DELETED;
+ }
break;
- case OC_EH_RESOURCE_CREATED:
- caResult = CA_CREATED;
+ case OC_EH_SLOW: // 2.05
+ caResult = CA_CONTENT;
break;
- case OC_EH_RESOURCE_DELETED:
- caResult = CA_DELETED;
+ case OC_EH_OK: // 2.04/2.05
+ if (method == OC_REST_POST || method == OC_REST_PUT)
+ {
+ caResult = CA_CHANGED;
+ }
+ else if (method == OC_REST_GET)
+ {
+ caResult = CA_CONTENT;
+ }
break;
- case OC_EH_SLOW:
- caResult = CA_CONTENT;
+ case OC_EH_VALID: // 2.03
+ caResult = CA_VALID;
break;
- case OC_EH_FORBIDDEN:
+ case OC_EH_CHANGED: // 2.04
+ caResult = CA_CHANGED;
+ break;
+ // Unsuccessful Client Request
+ case OC_EH_UNAUTHORIZED_REQ: // 4.01
caResult = CA_UNAUTHORIZED_REQ;
break;
- case OC_EH_RESOURCE_NOT_FOUND:
+ case OC_EH_BAD_OPT: // 4.02
+ caResult = CA_BAD_OPT;
+ break;
+ case OC_EH_FORBIDDEN: // 4.03
+ caResult = CA_FORBIDDEN_REQ;
+ break;
+ case OC_EH_RESOURCE_NOT_FOUND: // 4.04
caResult = CA_NOT_FOUND;
break;
+ case OC_EH_METHOD_NOT_ALLOWED: // 4.05
+ caResult = CA_METHOD_NOT_ALLOWED;
+ break;
+ case OC_EH_NOT_ACCEPTABLE: // 4.06
+ caResult = CA_NOT_ACCEPTABLE;
+ break;
+ case OC_EH_INTERNAL_SERVER_ERROR: // 5.00
+ caResult = CA_INTERNAL_SERVER_ERROR;
+ break;
+ case OC_EH_RETRANSMIT_TIMEOUT: // 5.04
+ caResult = CA_RETRANSMIT_TIMEOUT;
+ break;
default:
caResult = CA_BAD_REQ;
break;
CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
+ responseInfo.info.messageId = serverRequest->coapID;
responseInfo.info.resourceUri = serverRequest->resourceUrl;
responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult, serverRequest->method);
else if(!serverRequest->notificationFlag && serverRequest->slowFlag &&
serverRequest->qos == OC_HIGH_QOS)
{
+ // To assign new messageId in CA.
+ responseInfo.info.messageId = 0;
responseInfo.info.type = CA_MSG_CONFIRM;
}
else if(!serverRequest->notificationFlag)
(OCRepPayload*)newPayload);
}
-
(serverRequest->numResponses)--;
if(serverRequest->numResponses == 0)
exit:
return stackRet;
}
-
NULL, PAYLOAD_TYPE_REPRESENTATION,
NULL, 0, 0, NULL,
OC_OBSERVE_DEREGISTER,
- observer->observeId);
+ observer->observeId,
+ 0);
if(result != OC_STACK_OK)
{
return result;
NULL, PAYLOAD_TYPE_REPRESENTATION,
NULL, 0, 0, NULL,
OC_OBSERVE_DEREGISTER,
- observer->observeId);
+ observer->observeId,
+ 0);
if(result != OC_STACK_OK)
{
return OC_STACK_ERROR;
OCClientResponse response =
{.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
- response.sequenceNumber = OC_OBSERVE_NO_OPTION;
+ response.sequenceNumber = -1;
CopyEndpointToDevAddr(endPoint, &response.devAddr);
FixUpClientResponse(&response);
response.resourceUri = responseInfo->info.resourceUri;
requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
}
- if (result != OC_STACK_OK)
- {
- OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
- goto exit;
- }
-
// prepare for response
#ifdef WITH_PRESENCE
if (method == OC_REST_PRESENCE)
previous = pointer;
pointer = pointer->next;
}
- previous->next = newInterface;
+
+ if (previous)
+ {
+ previous->next = newInterface;
+ }
}
}
if (id)
{
OICStrcpy((char*)tags->di.id, MAX_IDENTITY_SIZE, (char *)id);
- if (!tags->di.id)
- {
- goto memory_allocation_failed;
- }
}
if (baseURI)
{
//Set of strings for each of device info fields
std::string deviceName = "Bill's Battlestar";
std::string specVersion = "myDeviceSpecVersion";
-std::string dataModleVersion = "myDeviceModleVersion";
+std::string dataModelVersions = "myDeviceModelVersion";
//OCPlatformInfo Contains all the platform info to be stored
OCPlatformInfo platformInfo;
{
delete[] deviceInfo.deviceName;
delete[] deviceInfo.specVersion;
- delete[] deviceInfo.dataModleVersion;
+ OCFreeOCStringLL(deviceInfo.dataModelVersions);
}
void DuplicateString(char ** targetString, std::string sourceString)
}
-OCStackResult SetDeviceInfo(std::string deviceName, std::string specVersion, std::string dataModleVersion)
+OCStackResult SetDeviceInfo(std::string deviceName, std::string specVersion, std::string dataModelVersions)
{
DuplicateString(&deviceInfo.deviceName, deviceName);
if (!specVersion.empty())
DuplicateString(&deviceInfo.specVersion, specVersion);
- if (!dataModleVersion.empty())
- DuplicateString(&deviceInfo.dataModleVersion, dataModleVersion);
+ if (!dataModelVersions.empty())
+ OCResourcePayloadAddStringLL(&deviceInfo.dataModelVersions, dataModelVersions.c_str());
return OC_STACK_OK;
}
}
- result = SetDeviceInfo(deviceName, specVersion, dataModleVersion);
+ result = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
std::string clientAPIVersion;
std::string clientToken;
+ // Get the message ID from the request
+ std::cout << " MessageID: " << request->getMessageID() << std::endl;
+
// Search the header options map and look for API version and Client token
for (auto it = headerOptions.begin(); it != headerOptions.end(); ++it)
{
{
try
{
- if(eCode == OC_STACK_OK && sequenceNumber != OC_OBSERVE_NO_OPTION)
+ if(eCode == OC_STACK_OK && sequenceNumber != -1)
{
if(sequenceNumber == OC_OBSERVE_REGISTER)
{
std::cout << "Observe registration action is successful" << std::endl;
}
- else if(sequenceNumber == OC_OBSERVE_DEREGISTER)
- {
- std::cout << "Observe De-registration action is successful" << std::endl;
- }
std::cout << "OBSERVE RESULT:"<<std::endl;
std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;
}
else
{
- if(sequenceNumber == OC_OBSERVE_NO_OPTION)
+ if(eCode == OC_STACK_OK)
{
- std::cout << "Observe registration or de-registration action is failed" << std::endl;
+ std::cout << "Observe registration failed or de-registration action failed/succeeded" << std::endl;
}
else
{
OC::ModeType::Both,
"0.0.0.0",
0,
- OC::QualityOfService::LowQos,
+ OC::QualityOfService::HighQos,
&ps
};
const std::vector<std::string>& getResourceTypes() const;
+ const std::vector<std::string>& getDataModelVersions() const;
+
void setResourceTypes(const std::vector<std::string>& resourceTypes);
void addResourceType(const std::string& str);
void addResourceInterface(const std::string& str);
+ void addDataModelVersion(const std::string& str);
+
bool emptyData() const;
int numberOfAttributes() const;
mutable std::map<std::string, AttributeValue> m_values;
std::vector<std::string> m_resourceTypes;
std::vector<std::string> m_interfaces;
+ std::vector<std::string> m_dataModelVersions;
InterfaceType m_interfaceType;
};
m_resourceUri{},
m_queryParameters{},
m_requestHandlerFlag{},
+ m_messageID{},
m_representation{},
m_observationInfo{},
m_headerOptions{},
return m_resourceHandle;
}
+ /**
+ * This API retrieves the request message ID
+ *
+ * @return int16_t value of message ID
+ */
+ int16_t getMessageID() const {return m_messageID;}
+
private:
std::string m_requestType;
std::string m_resourceUri;
QueryParamsMap m_queryParameters;
int m_requestHandlerFlag;
+ int16_t m_messageID;
OCRepresentation m_representation;
ObservationInfo m_observationInfo;
HeaderOptions m_headerOptions;
m_requestHandlerFlag = requestHandlerFlag;
}
+ void setMessageID(int16_t messageID)
+ {
+ m_messageID = messageID;
+ }
+
void setObservationInfo(const ObservationInfo& observationInfo)
{
m_observationInfo = observationInfo;
{
pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
pRequest->setResourceHandle(entityHandlerRequest->resource);
+ pRequest->setMessageID(entityHandlerRequest->messageID);
}
if(flag & OC_REQUEST_FLAG)
rep[OC_RSRVD_SPEC_VERSION] = payload->specVersion ?
std::string(payload->specVersion) :
std::string();
- rep[OC_RSRVD_DATA_MODEL_VERSION] = payload->dataModelVersion ?
- std::string(payload->dataModelVersion) :
- std::string();
+ for (OCStringLL *strll = payload->dataModelVersions; strll; strll = strll->next)
+ {
+ rep.addDataModelVersion(strll->value);
+ }
for (OCStringLL *strll = payload->types; strll; strll = strll->next)
{
rep.addResourceType(strll->value);
m_interfaces = resourceInterfaces;
}
+ const std::vector<std::string>& OCRepresentation::getDataModelVersions() const
+ {
+ return m_dataModelVersions;
+ }
+
+ void OCRepresentation::addDataModelVersion(const std::string& str)
+ {
+ m_dataModelVersions.push_back(str);
+ }
+
bool OCRepresentation::hasAttribute(const std::string& str) const
{
return m_values.find(str) != m_values.end();
else if ((m_interfaceType == InterfaceType::None
|| m_interfaceType==InterfaceType::DefaultChild
|| m_interfaceType==InterfaceType::LinkChild)
- && (m_resourceTypes.size()>0 || m_interfaces.size()>0))
+ && (m_resourceTypes.size()>0 || m_interfaces.size()>0
+ || m_dataModelVersions.size()>0))
{
return false;
}
delete[] deviceInfo.deviceName;
DeleteStringLL(deviceInfo.types);
delete[] deviceInfo.specVersion;
- delete[] deviceInfo.dataModleVersion;
+ DeleteStringLL(deviceInfo.dataModelVersions);
}
void DuplicateString(char ** targetString, std::string sourceString)
OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
DuplicateString(&deviceInfo.specVersion, "mySpecVersion");
- DuplicateString(&deviceInfo.dataModleVersion, "myDataModleVersion");
+ deviceInfo.dataModelVersions = nullptr;
+ OCResourcePayloadAddStringLL(&deviceInfo.dataModelVersions, "myDataModelVersions");
EXPECT_EQ(OC_STACK_OK, OCPlatform::registerDeviceInfo(deviceInfo));
EXPECT_NO_THROW(DeleteDeviceInfo(deviceInfo));
}
static const char sid1[] = "646F6F72-4465-7669-6365-555549443030";
static const char devicename1[] = "device name";
static const char specver1[] = "spec version";
- static const char dmver1[] = "data model version";
+ static const char dmver1[] = "res.1.1.0,sh.1.1.0";
static OCStringLL *types = NULL;
// Device Payloads
TEST(DeviceDiscoveryEncoding, Normal)
types,
specver1,
dmver1);
+ EXPECT_TRUE(device);
EXPECT_STREQ(sid1, device->sid);
EXPECT_STREQ(devicename1, device->deviceName);
EXPECT_STREQ(specver1, device->specVersion);
- EXPECT_STREQ(dmver1, device->dataModelVersion);
+ EXPECT_TRUE(device->dataModelVersions);
+ EXPECT_STREQ("res.1.1.0", device->dataModelVersions->value);
+ EXPECT_TRUE(device->dataModelVersions->next);
+ EXPECT_STREQ("sh.1.1.0", device->dataModelVersions->next->value);
EXPECT_EQ(PAYLOAD_TYPE_DEVICE, ((OCPayload*)device)->type);
EXPECT_STREQ("oic.wk.d", device->types->value);
EXPECT_STREQ("oic.d.tv", device->types->next->value);
EXPECT_STREQ(device->sid, ((OCDevicePayload*)parsedDevice)->sid);
EXPECT_STREQ(device->deviceName, ((OCDevicePayload*)parsedDevice)->deviceName);
EXPECT_STREQ(device->specVersion, ((OCDevicePayload*)parsedDevice)->specVersion);
- EXPECT_STREQ(device->dataModelVersion, ((OCDevicePayload*)parsedDevice)->dataModelVersion);
+ EXPECT_STREQ(device->dataModelVersions->value, ((OCDevicePayload*)parsedDevice)->dataModelVersions->value);
EXPECT_STREQ("oic.wk.d", ((OCDevicePayload*)parsedDevice)->types->value);
EXPECT_STREQ("oic.d.tv", ((OCDevicePayload*)parsedDevice)->types->next->value);
EXPECT_EQ(device->base.type, ((OCDevicePayload*)parsedDevice)->base.type);
EXPECT_STREQ(sid1, r.getValue<std::string>(OC_RSRVD_DEVICE_ID).c_str());
EXPECT_STREQ(devicename1, r.getValue<std::string>(OC_RSRVD_DEVICE_NAME).c_str());
EXPECT_STREQ(specver1, r.getValue<std::string>(OC_RSRVD_SPEC_VERSION).c_str());
- EXPECT_STREQ(dmver1, r.getValue<std::string>(OC_RSRVD_DATA_MODEL_VERSION).c_str());
+ EXPECT_STREQ("res.1.1.0", r.getDataModelVersions()[0].c_str());
+ EXPECT_STREQ("sh.1.1.0", r.getDataModelVersions()[1].c_str());
OCPayloadDestroy(parsedDevice);
}
int setCode = 200;
EXPECT_NO_THROW(response.setErrorCode(setCode));
EXPECT_EQ(setCode, response.getErrorCode());
+ setCode = 500;
+ EXPECT_NO_THROW(response.setErrorCode(setCode));
+ EXPECT_EQ(setCode, response.getErrorCode());
+ setCode = 400;
+ EXPECT_NO_THROW(response.setErrorCode(setCode));
+ EXPECT_EQ(setCode, response.getErrorCode());
}
TEST(NewResourceUriTest, SetGetNewResourceUriValidUri)
$(LOCAL_PATH)/../../../../../../resource/include \
$(LOCAL_PATH)/../../../../../../resource/c_common \
$(LOCAL_PATH)/../../../../../../resource/oc_logger/include \
- $(LOCAL_PATH)/../../../../../../resource/csdk/ocmalloc/include \
+ $(LOCAL_PATH)/../../../../../../resource/c_common/oic_malloc/include \
$(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/api \
$(LOCAL_PATH)/../../../../../../resource/csdk/stack/include \
$(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
mediator_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
mediator_env.PrependUnique(CPPPATH = [
- env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',
+ env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
env.get('SRC_DIR') + '/resource/csdk/connectivity/common/inc',
env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
env.get('SRC_DIR') + '/resource/csdk/stack/include',
mediator_env.PrependUnique(CPPPATH = [
env.get('SRC_DIR') + '/resource/include',
env.get('SRC_DIR') + '/resource/oc_logger/include',
- env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',
+ env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
env.get('SRC_DIR') + '/resource/csdk/stack/include',
env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
const RCSResourceAttributes &value,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(value);
}
RCSResourceAttributes BMISensorResource::handleGetAttributesRequest(const
std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
const RCSResourceAttributes &value,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(value);
}
RCSResourceAttributes DiscomfortIndexSensorResource::handleGetAttributesRequest(
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(attr);
}
virtual RCSResourceAttributes handleGetAttributesRequest(const
std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
};
virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(attr);
}
virtual RCSResourceAttributes handleGetAttributesRequest(const
std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
};
virtual void handleSetAttributesRequest(const RCSResourceAttributes &attr,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(attr);
}
virtual RCSResourceAttributes handleGetAttributesRequest(const
std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
RCSResourceAttributes handleGetAttributesRequest(
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
return BundleResource::getAttributes();
}
const RCSResourceAttributes &value,
const std::map< std::string, std::string > &queryParams)
{
+ (void)queryParams;
BundleResource::setAttributes(value);
}
};
out << "Platform version: " << platformInfo.getPlatformVersion() << std::endl;
out << "Manufacturer name: " << platformInfo.getManufacturerName() << std::endl;
out << "Manufacturer url: " << platformInfo.getManufacturerUrl() << std::endl;
- out << "Modle number: " << platformInfo.getModelNumber() << std::endl;
+ out << "Model number: " << platformInfo.getModelNumber() << std::endl;
out << "Date of manufacture: " << platformInfo.getDateOfManfacture() << std::endl;
out << "Operatio system version: " << platformInfo.getOSVersion() << std::endl;
out << "Hardware version: " << platformInfo.getHardwareVersion() << std::endl;
cp -r resource/csdk/stack/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/csdk/ocsocket/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/c_common/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/csdk/ocmalloc/include/*.h $FRAMEWORK_BUNDLE/Headers
+cp -r resource/c_common/oic_malloc/include/*.h $FRAMEWORK_BUNDLE/Headers
echo "Framework: Creating plist..."
cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
echo "Framework: Copying includes..."
cp -r resource/csdk/stack/include/*.h $FRAMEWORK_BUNDLE/Headers
cp -r resource/c_common/ocrandom/include/*.h $FRAMEWORK_BUNDLE/Headers
-cp -r resource/csdk/ocmalloc/include/*.h $FRAMEWORK_BUNDLE/Headers
+cp -r resource/c_common/oic_malloc/include/*.h $FRAMEWORK_BUNDLE/Headers
echo "Framework: Creating plist..."
cat > $FRAMEWORK_BUNDLE/Resources/Info.plist <<EOF
Name: iotivity
-Version: 1.1.0
+Version: 1.1.1
Release: 0
Summary: IoT Connectivity sponsored by the OIC
Group: Network & Connectivity/Other