Merge branch 'windows-port'
authorDavid Antler <david.a.antler@intel.com>
Fri, 1 Jul 2016 21:28:42 +0000 (14:28 -0700)
committerDavid Antler <david.a.antler@intel.com>
Fri, 1 Jul 2016 21:28:42 +0000 (14:28 -0700)
Add support for Visual Studio 2015 and 2013 builds.

Change-Id: I3ce9bee6b3e57ccd548b849b5d147ca0babd872e
Signed-off-by: David Antler <david.a.antler@intel.com>
183 files changed:
android/android_api/base/jni/Android.mk
android/android_api/base/jni/JniCaInterface.c
android/android_api/base/jni/JniDisplayPinListener.cpp
android/android_api/base/jni/JniEntityHandler.cpp
android/android_api/base/jni/JniListenerManager.h
android/android_api/base/jni/JniOcDirectPairDevice.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOcDirectPairDevice.h [new file with mode: 0644]
android/android_api/base/jni/JniOcPlatform.cpp
android/android_api/base/jni/JniOcPlatform.h
android/android_api/base/jni/JniOcPresenceHandle.cpp
android/android_api/base/jni/JniOcRepresentation.cpp
android/android_api/base/jni/JniOcRepresentation.h
android/android_api/base/jni/JniOcRequestHandle.cpp
android/android_api/base/jni/JniOcResource.cpp
android/android_api/base/jni/JniOcResourceHandle.cpp
android/android_api/base/jni/JniOcResourceIdentifier.cpp
android/android_api/base/jni/JniOcResourceRequest.cpp
android/android_api/base/jni/JniOcResourceResponse.cpp
android/android_api/base/jni/JniOcSecureResource.cpp
android/android_api/base/jni/JniOcSecureResource.h
android/android_api/base/jni/JniOcStack.cpp
android/android_api/base/jni/JniOcStack.h
android/android_api/base/jni/JniOnDPDevicesFoundListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnDPDevicesFoundListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnDeleteListener.cpp
android/android_api/base/jni/JniOnDeviceInfoListener.cpp
android/android_api/base/jni/JniOnDirectPairingListener.cpp [new file with mode: 0644]
android/android_api/base/jni/JniOnDirectPairingListener.h [new file with mode: 0644]
android/android_api/base/jni/JniOnGetListener.cpp
android/android_api/base/jni/JniOnObserveListener.cpp
android/android_api/base/jni/JniOnPlatformInfoListener.cpp
android/android_api/base/jni/JniOnPostListener.cpp
android/android_api/base/jni/JniOnPresenceListener.cpp
android/android_api/base/jni/JniOnPutListener.cpp
android/android_api/base/jni/JniOnResourceFoundListener.cpp
android/android_api/base/jni/JniPinCheckListener.cpp
android/android_api/base/jni/JniProvisionResultListner.cpp
android/android_api/base/jni/JniProvisionResultListner.h
android/android_api/base/jni/JniSecureUtils.cpp
android/android_api/base/jni/JniSecureUtils.h
android/android_api/base/jni/JniUtils.cpp
android/android_api/base/jni/JniUtils.h
android/android_api/base/src/main/java/org/iotivity/base/OcDirectPairDevice.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java
android/android_api/base/src/main/java/org/iotivity/base/OcPrmType.java [new file with mode: 0755]
android/android_api/base/src/main/java/org/iotivity/base/OcSecureResource.java
android/android_api/base/src/main/java/org/iotivity/base/OicSecPdAcl.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/ca/CaBtPairingInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaEdrInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaIpInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaLeClientInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaNfcInterface.java
android/examples/DirectPairing/.classpath [new file with mode: 0644]
android/examples/DirectPairing/.project [new file with mode: 0644]
android/examples/DirectPairing/DirectPairing.iml [new file with mode: 0644]
android/examples/DirectPairing/build.gradle [new file with mode: 0644]
android/examples/DirectPairing/project.properties [new file with mode: 0644]
android/examples/DirectPairing/src/main/AndroidManifest.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat [new file with mode: 0644]
android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/ExpandableListAdapter.java [new file with mode: 0644]
android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/Led.java [new file with mode: 0644]
android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/MainActivity.java [new file with mode: 0644]
android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/StringConstants.java [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/activity_main.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/custom_list_view.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/group_indicator.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/list_group.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/layout/list_item.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/menu/main.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values-v11/styles.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values-v14/styles.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values-w820dp/dimens.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values/dimens.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values/strings.xml [new file with mode: 0644]
android/examples/DirectPairing/src/main/res/values/styles.xml [new file with mode: 0644]
android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/ProvisioningClient.java
android/examples/settings.gradle
build_common/SConscript
examples/OICMiddle/WrapResource.h
plugins/samples/linux/IotivityandZigbeeServer.c
resource/csdk/connectivity/common/src/camutex_pthreads.c
resource/csdk/connectivity/inc/catcpinterface.h
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c
resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.c
resource/csdk/connectivity/src/cablockwisetransfer.c
resource/csdk/connectivity/src/caconnectivitymanager.c
resource/csdk/connectivity/src/cainterfacecontroller.c
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/caqueueingthread.c
resource/csdk/connectivity/src/caretransmission.c
resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/nfc_adapter/android/canfcserver.c
resource/csdk/connectivity/src/tcp_adapter/catcpserver.c
resource/csdk/connectivity/test/cablocktransfertest.cpp
resource/csdk/connectivity/util/src/btpairing/android/cabtpairing.c
resource/csdk/connectivity/util/src/camanager/android/caleconnectionmanager.c
resource/csdk/security/include/internal/credresource.h
resource/csdk/security/include/internal/srmresourcestrings.h
resource/csdk/security/include/securevirtualresourcetypes.h
resource/csdk/security/provisioning/SConscript
resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c
resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp
resource/csdk/security/provisioning/include/internal/credentialgenerator.h
resource/csdk/security/provisioning/include/internal/secureresourceprovider.h
resource/csdk/security/provisioning/include/ocprovisioningmanager.h
resource/csdk/security/provisioning/sample/provisioningclient.c
resource/csdk/security/provisioning/src/credentialgenerator.c
resource/csdk/security/provisioning/src/ocprovisioningmanager.c
resource/csdk/security/provisioning/src/ownershiptransfermanager.c
resource/csdk/security/provisioning/src/pmutility.c
resource/csdk/security/provisioning/src/secureresourceprovider.c
resource/csdk/security/provisioning/unittest/SConscript
resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp [new file with mode: 0644]
resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp
resource/csdk/security/provisioning/unittest/otmunittest.cpp
resource/csdk/security/provisioning/unittest/sampleserver1.cpp
resource/csdk/security/provisioning/unittest/sampleserver2.cpp
resource/csdk/security/src/aclresource.c
resource/csdk/security/src/amaclresource.c
resource/csdk/security/src/amsmgr.c
resource/csdk/security/src/credresource.c
resource/csdk/security/src/crlresource.c
resource/csdk/security/src/doxmresource.c
resource/csdk/security/src/dpairingresource.c [changed mode: 0755->0644]
resource/csdk/security/src/pconfresource.c
resource/csdk/security/src/pstatresource.c
resource/csdk/security/src/srmresourcestrings.c
resource/csdk/security/src/svcresource.c
resource/csdk/security/src/verresource.c
resource/csdk/security/tool/json2cbor.c
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/credentialresource.cpp
resource/csdk/stack/include/internal/ocserverrequest.h
resource/csdk/stack/include/internal/ocstackinternal.h
resource/csdk/stack/include/ocpayload.h
resource/csdk/stack/include/octypes.h
resource/csdk/stack/include/payload_logging.h
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/samples/tizen/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec
resource/csdk/stack/src/ocobserve.c
resource/csdk/stack/src/ocpayload.c
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c [changed mode: 0755->0644]
resource/csdk/stack/src/ocresource.c
resource/csdk/stack/src/ocserverrequest.c
resource/csdk/stack/src/ocstack.c
resource/csdk/stack/src/rdpayload.c
resource/examples/devicediscoveryserver.cpp
resource/examples/fridgeserver.cpp
resource/examples/simpleclient.cpp
resource/include/OCRepresentation.h
resource/include/OCResourceRequest.h
resource/src/InProcServerWrapper.cpp
resource/src/OCRepresentation.cpp
resource/unittests/OCPlatformTest.cpp
resource/unittests/OCRepresentationEncodingTest.cpp
resource/unittests/OCResourceResponseTest.cpp
service/easy-setup/mediator/richsdk/android/jni/Android.mk
service/easy-setup/sampleapp/mediator/linux/csdk_sample/SConscript
service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript
service/resource-container/examples/BMISensorBundle/src/BMISensorResource.cpp
service/resource-container/examples/DiscomfortIndexSensorBundle/src/DiscomfortIndexSensorResource.cpp
service/resource-container/unittests/ResourceContainerTest.cpp
service/resource-container/unittests/TestBundle/include/TestBundleActivator.h
service/simulator/examples/client/simulator_client.cpp
tools/darwin/mkfwk_ios.sh
tools/darwin/mkfwk_osx.sh
tools/tizen/iotivity.spec

index cc43275..a513cb1 100644 (file)
@@ -58,7 +58,7 @@ LOCAL_SRC_FILES :=  JniOcStack.cpp \
                     JniEntityHandler.cpp \\r
                     JniOnResourceFoundListener.cpp \\r
                     JniOnDeviceInfoListener.cpp \\r
-                   JniOnPlatformInfoListener.cpp \\r
+                    JniOnPlatformInfoListener.cpp \\r
                     JniOnPresenceListener.cpp \\r
                     JniOnGetListener.cpp \\r
                     JniOnPutListener.cpp \\r
@@ -74,15 +74,18 @@ LOCAL_SRC_FILES :=  JniOcStack.cpp \
                     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
index 81fcd81..e8649ec 100644 (file)
@@ -74,7 +74,7 @@ void CAManagerConnectionStateChangedCB(CATransportAdapter_t adapter,
     }
 
     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)
     {
@@ -155,7 +155,7 @@ void CAManagerAdapterStateChangedCB(CATransportAdapter_t adapter, bool enabled)
     }
 
     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)
     {
index 25ee926..1705bdf 100644 (file)
@@ -33,7 +33,7 @@ JniDisplayPinListener::~JniDisplayPinListener()
     LOGI("~JniDisplayPinListener()");
     if (m_jgListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
         if (NULL == env) return;
         env->DeleteGlobalRef(m_jgListener);
@@ -43,9 +43,12 @@ JniDisplayPinListener::~JniDisplayPinListener()
 
 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);
 
index 1d641ae..f46dde0 100644 (file)
@@ -33,7 +33,7 @@ JniEntityHandler::~JniEntityHandler()
     LOGD("~JniEntityHandler");
     if (m_jListener)
     {
-        jint ret;
+        jint ret = JNI_ERR;
         JNIEnv *env = GetJNIEnv(ret);
         if (nullptr == env)
         {
@@ -54,7 +54,7 @@ OCEntityHandlerResult JniEntityHandler::handleEntity(
     const std::shared_ptr<OCResourceRequest> request)
 {
     LOGD("JniEntityHandler_handleEntity");
-    jint envRet;
+    jint envRet = JNI_ERR;
     JNIEnv *env = GetJNIEnv(envRet);
     if (nullptr == env)
     {
@@ -133,7 +133,10 @@ OCEntityHandlerResult JniEntityHandler::handleEntity(
     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);
index b082f7d..989dd3d 100644 (file)
@@ -51,6 +51,7 @@ public:
                 break;
             }
         }
+
         if (!onEventListener)
         {
             onEventListener = new T(env, jListener, owner);
@@ -66,9 +67,11 @@ public:
             {
                 LOGD("OnEventListener: Failed to create global listener ref.");
                 delete onEventListener;
+                return nullptr;
             }
             LOGD("OnEventListener: new listener");
         }
+
         m_mapMutex.unlock();
         return onEventListener;
     }
diff --git a/android/android_api/base/jni/JniOcDirectPairDevice.cpp b/android/android_api/base/jni/JniOcDirectPairDevice.cpp
new file mode 100644 (file)
index 0000000..ff4e626
--- /dev/null
@@ -0,0 +1,145 @@
+/*
+* //******************************************************************
+* //
+* // 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);
+}
diff --git a/android/android_api/base/jni/JniOcDirectPairDevice.h b/android/android_api/base/jni/JniOcDirectPairDevice.h
new file mode 100644 (file)
index 0000000..505bac2
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+* //******************************************************************
+* //
+* // 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
+
index 8987a69..5678341 100644 (file)
@@ -25,6 +25,7 @@
 #include "JniOcPresenceHandle.h"
 #include "JniOcResourceResponse.h"
 #include "JniOcSecurity.h"
+#include "JniOcDirectPairDevice.h"
 #include "JniUtils.h"
 #include "ocpayload.h"
 
@@ -321,6 +322,148 @@ void RemoveOnPresenceListener(JNIEnv* env, jobject jListener)
     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
@@ -377,7 +520,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers0
 
     JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(
         env, jResourceHandle);
-    if (!jniOcResourceHandle) return;
+    if (!jniOcResourceHandle)
+    {
+        return;
+    }
 
     try
     {
@@ -420,7 +566,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers1
         return;
     }
 
-    try{
+    try {
         OCStackResult result = OCPlatform::notifyAllObservers(
             jniOcResourceHandle->getOCResourceHandle(),
             JniUtils::getQOS(env, static_cast<int>(jQoS)));
@@ -704,6 +850,145 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findResource1(
 }
 
 /*
+ * 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
@@ -950,7 +1235,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_registerResource0(
         return nullptr;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, jResource);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     OCResourceHandle resourceHandle;
     try
@@ -1100,12 +1388,17 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerDeviceInfo0(
             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);
         }
@@ -1324,7 +1617,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindResource0
     }
     JniOcResourceHandle* jniOcResourceCollectionHandle =
         JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceCollectionHandle);
-    if (!jniOcResourceCollectionHandle) return;
+    if (!jniOcResourceCollectionHandle)
+    {
+        return;
+    }
 
     JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(
         env, jResourceHandle);
@@ -1575,7 +1871,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindTypeToResource0(
 
     JniOcResourceHandle* jniOcResourceHandle =
         JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
-    if (!jniOcResourceHandle) return;
+    if (!jniOcResourceHandle)
+    {
+        return;
+    }
 
     try
     {
@@ -1975,7 +2274,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_sendResponse0(
 
     JniOcResourceResponse *jniResponse =
         JniOcResourceResponse::getJniOcResourceResponsePtr(env, jResourceResponse);
-    if (!jniResponse) return;
+    if (!jniResponse)
+    {
+        return;
+    }
 
     try
     {
index c66ad43..a45f059 100644 (file)
@@ -23,6 +23,8 @@
 #include "JniOnResourceFoundListener.h"
 #include "JniOnDeviceInfoListener.h"
 #include "JniOnPlatformInfoListener.h"
+#include "JniOnDPDevicesFoundListener.h"
+#include "JniOnDirectPairingListener.h"
 #include "JniOnPresenceListener.h"
 #include <mutex>
 
@@ -43,15 +45,26 @@ void RemoveOnPlatformInfoListener(JNIEnv* env, jobject jListener);
 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" {
@@ -288,6 +301,30 @@ 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
index 00f81a1..28b7859 100644 (file)
@@ -24,7 +24,8 @@
 
 JniOcPresenceHandle::JniOcPresenceHandle(JniOnPresenceListener* jniListener, OCPresenceHandle presenceHandle)
     : m_jniListener(jniListener), m_presenceHandle(presenceHandle)
-{}
+{
+}
 
 JniOcPresenceHandle::~JniOcPresenceHandle()
 {
@@ -70,4 +71,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPresenceHandle_dispose
     LOGD("OcPresenceHandle_dispose");
     JniOcPresenceHandle *presenceHandle = JniOcPresenceHandle::getJniOcPresenceHandlePtr(env, thiz);
     delete presenceHandle;
-}
\ No newline at end of file
+}
index 1403349..042e2a4 100644 (file)
@@ -51,13 +51,20 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValues
 {
     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);
@@ -80,7 +87,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getValueN
         return nullptr;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return nullptr;
+    if (!rep)
+    {
+        return nullptr;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
 
@@ -108,7 +118,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger
         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));
@@ -129,7 +142,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble
         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));
@@ -150,7 +166,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean
         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));
@@ -171,7 +190,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueStringN
         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);
@@ -194,14 +216,20 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresent
         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
@@ -236,7 +264,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueIntegerAr
     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);
@@ -274,7 +305,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger2D
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -320,7 +354,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueInteger3D
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -352,7 +389,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDoubleArr
     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);
@@ -390,7 +430,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble2DA
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -436,7 +479,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueDouble3DA
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -468,7 +514,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBooleanAr
     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);
@@ -507,7 +556,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean2D
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -554,7 +606,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueBoolean3D
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -579,7 +634,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueStringArr
     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);
@@ -611,7 +669,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueString2DA
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -651,8 +712,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueString3DA
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
-
+    if (!rep)
+    {
+        return;
+    }
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
 }
@@ -676,7 +739,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresent
     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);
@@ -708,7 +774,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresent
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -748,7 +817,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueRepresent
     }
 
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string key = env->GetStringUTFChars(jKey, nullptr);
     rep->setValue(key, value);
@@ -780,7 +852,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setValueByteArray
     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);
@@ -796,10 +871,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_addChild
 {
     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);
 }
@@ -814,7 +895,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_clearChildren
 {
     LOGD("OcRepresentation_clearChildren");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     rep->clearChildren();
 }
@@ -829,7 +913,10 @@ JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcRepresentation_getChildr
 {
     LOGD("OcRepresentation_getChildrenArray");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return nullptr;
+    if (!rep)
+    {
+        return nullptr;
+    }
 
     return JniUtils::convertRepresentationVectorToJavaArray(env, rep->getChildren());
 }
@@ -844,7 +931,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getUri
 {
     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());
@@ -860,7 +950,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getHost
 {
     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());
@@ -881,7 +974,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setUri
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     rep->setUri(env->GetStringUTFChars(jUri, nullptr));
 }
@@ -896,7 +992,10 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_hasAttribute
         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);
@@ -912,7 +1011,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getResourceTyp
 {
     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);
@@ -933,7 +1035,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setResourceTypeAr
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::vector<std::string> resourceTypes;
     JniUtils::convertJavaStrArrToStrVector(env, jResourceTypeArray, resourceTypes);
@@ -949,7 +1054,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcRepresentation_getResourceInt
 {
     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);
@@ -970,7 +1078,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setResourceInterf
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::vector<std::string> resourceInterfaces;
     JniUtils::convertJavaStrArrToStrVector(env, jResourceInterfaceArray, resourceInterfaces);
@@ -987,7 +1098,10 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_isEmpty
 {
     LOGD("OcRepresentation_isEmpty");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return false;
+    if (!rep)
+    {
+        return false;
+    }
 
     return static_cast<jboolean>(rep->empty());
 }
@@ -1002,7 +1116,10 @@ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcRepresentation_size
 {
     LOGD("OcRepresentation_size");
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return -1;
+    if (!rep)
+    {
+        return -1;
+    }
 
     return static_cast<jint>(rep->numberOfAttributes());
 }
@@ -1022,7 +1139,10 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_remove
         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));
@@ -1043,7 +1163,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRepresentation_setNull
         return;
     }
     OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
-    if (!rep) return;
+    if (!rep)
+    {
+        return;
+    }
 
     std::string attributeKey = env->GetStringUTFChars(jAttributeKey, nullptr);
     rep->setNULL(attributeKey);
@@ -1064,7 +1187,10 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcRepresentation_isNull
         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));
index a153dd7..e9acd35 100644 (file)
@@ -35,9 +35,15 @@ public:
 
 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(
@@ -87,7 +93,10 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
@@ -96,7 +105,10 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
@@ -105,13 +117,20 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
     }
@@ -119,12 +138,18 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
@@ -133,7 +158,10 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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]);
@@ -159,7 +187,10 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
@@ -178,12 +209,21 @@ struct JObjectConverter : boost::static_visitor < jobject >
         {
             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;
@@ -192,26 +232,46 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
@@ -221,17 +281,31 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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);
         }
 
@@ -241,26 +315,44 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
@@ -270,22 +362,38 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
@@ -294,31 +402,49 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
     }
@@ -327,21 +453,33 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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);
         }
 
@@ -351,30 +489,48 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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;
@@ -384,12 +540,18 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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]);
@@ -402,11 +564,17 @@ struct JObjectConverter : boost::static_visitor < jobject >
                     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;
@@ -415,17 +583,26 @@ struct JObjectConverter : boost::static_visitor < jobject >
     {
         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]);
@@ -438,15 +615,24 @@ struct JObjectConverter : boost::static_visitor < jobject >
                         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;
index b916490..9585c55 100644 (file)
@@ -22,7 +22,8 @@
 #include "JniOcRequestHandle.h"
 
 JniOcRequestHandle::JniOcRequestHandle(OCRequestHandle requestHandle) : m_requestHandle(requestHandle)
-{}
+{
+}
 
 JniOcRequestHandle::~JniOcRequestHandle()
 {
@@ -60,4 +61,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcRequestHandle_dispose
     LOGD("OcRequestHandle_dispose");
     JniOcRequestHandle *handle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, thiz);
     delete handle;
-}
\ No newline at end of file
+}
index 9e6925a..743c1bc 100644 (file)
@@ -26,7 +26,8 @@
 
 JniOcResource::JniOcResource(std::shared_ptr<OCResource> resource)
     : m_sharedResource(resource)
-{}
+{
+}
 
 JniOcResource::~JniOcResource()
 {
@@ -34,9 +35,12 @@ 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);
@@ -44,7 +48,10 @@ JniOcResource::~JniOcResource()
     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)
@@ -432,7 +439,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -476,7 +486,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_get1
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -533,7 +546,10 @@ jobject jQueryParamsMap, jobject jListener)
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -590,7 +606,10 @@ jobject jQueryParamsMap, jobject jListener, jint jQoS)
         resourceInterface = env->GetStringUTFChars(jResourceInterface, nullptr);
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -643,10 +662,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_put
         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);
@@ -698,10 +723,16 @@ jobject jListener, jint jQoS)
         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);
@@ -764,10 +795,16 @@ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
         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);
@@ -832,10 +869,16 @@ jobject jQueryParamsMap, jobject jListener, jint jQoS)
     }
 
     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);
@@ -888,10 +931,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post
         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);
@@ -941,10 +990,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_post1
         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);
@@ -1008,10 +1063,16 @@ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
     }
 
     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);
@@ -1076,10 +1137,16 @@ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener, jint jQoS)
     }
 
     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);
@@ -1122,7 +1189,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_deleteResource
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     try
     {
@@ -1157,7 +1227,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_deleteResource1
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     try
     {
@@ -1199,7 +1272,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_observe
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -1246,7 +1322,10 @@ jobject jListener, jint jQoS)
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     QueryParamsMap qpm;
     JniUtils::convertJavaMapToQueryParamsMap(env, jQueryParamsMap, qpm);
@@ -1282,7 +1361,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve1
 {
     LOGD("OcResource_cancelObserve1");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     try
     {
@@ -1317,7 +1399,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_setHeaderOptions
         return;
     }
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     HeaderOptions headerOptions;
     JniUtils::convertJavaHeaderOptionsArrToVector(env, jheaderOptionArr, headerOptions);
@@ -1335,7 +1420,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_unsetHeaderOptions
 {
     LOGD("OcResource_unsetHeaderOptions");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
+    if (!resource)
+    {
+        return;
+    }
 
     resource->unsetHeaderOptions();
 }
@@ -1350,7 +1438,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getHost
 {
     LOGD("OcResource_getHost");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     return env->NewStringUTF(resource->host().c_str());
 }
@@ -1365,7 +1456,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getUri
 {
     LOGD("OcResource_getUri");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     return env->NewStringUTF(resource->uri().c_str());
 }
@@ -1380,7 +1474,10 @@ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcResource_getConnectivityTypeN
 {
     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);
@@ -1396,6 +1493,11 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcResource_isObservable
 {
     LOGD("OcResource_isObservable");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
+    if (!resource)
+    {
+        return false;
+    }
+
     return (jboolean)resource->isObservable();
 }
 
@@ -1409,7 +1511,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getResourceTypes
 {
     LOGD("OcResource_getResourceTypes");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     std::vector<std::string> resourceTypes = resource->getResourceTypes();
 
@@ -1426,7 +1531,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getResourceInterface
 {
     LOGD("OcResource_getResourceInterfaces");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     std::vector<std::string> resourceInterfaces = resource->getResourceInterfaces();
 
@@ -1443,11 +1551,17 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResource_getUniqueIdentifier
 {
     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,
@@ -1469,7 +1583,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResource_getServerId
 {
     LOGD("OcResource_getServerId");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return nullptr;
+    if (!resource)
+    {
+        return nullptr;
+    }
 
     return env->NewStringUTF(resource->sid().c_str());
 }
@@ -1485,4 +1602,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_dispose
     LOGD("OcResource_dispose");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
     delete resource;
-}
\ No newline at end of file
+}
index 2d438f2..92371f4 100644 (file)
@@ -25,7 +25,8 @@ using namespace OC;
 
 JniOcResourceHandle::JniOcResourceHandle(OCResourceHandle resourceHandle)
     : m_resourceHandle(resourceHandle)
-{}
+{
+}
 
 JniOcResourceHandle::~JniOcResourceHandle()
 {
@@ -63,4 +64,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceHandle_dispose
     LOGD("OcResourceHandle_dispose");
     JniOcResourceHandle *resourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, thiz);
     delete resourceHandle;
-}
\ No newline at end of file
+}
index b0b7d65..beeb724 100644 (file)
@@ -24,7 +24,8 @@
 
 JniOcResourceIdentifier::JniOcResourceIdentifier(OC::OCResourceIdentifier resourceIdentifier)
     : m_resourceIdentifier(resourceIdentifier)
-{}
+{
+}
 
 JniOcResourceIdentifier::~JniOcResourceIdentifier()
 {
@@ -60,10 +61,16 @@ JNIEXPORT jboolean JNICALL Java_org_iotivity_base_OcResourceIdentifier_equalsN
 (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())
     {
@@ -86,4 +93,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceIdentifier_dispose
     LOGD("JniOcResourceIdentifier_dispose");
     JniOcResourceIdentifier *identifier = JniOcResourceIdentifier::getJniOcResourceIdentifierPtr(env, thiz);
     delete identifier;
-}
\ No newline at end of file
+}
index c943f70..c977bac 100644 (file)
@@ -29,10 +29,12 @@ using namespace OC;
 
 JniOcResourceRequest::JniOcResourceRequest(const std::shared_ptr<OCResourceRequest> request)
     : m_request(request)
-{}
+{
+}
 
 JniOcResourceRequest::~JniOcResourceRequest()
-{}
+{
+}
 
 std::string
 JniOcResourceRequest::getRequestType()
@@ -119,8 +121,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestTyp
 {
     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());
 }
@@ -135,7 +139,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getQueryParam
 {
     LOGD("OcResourceRequest_getQueryParameters");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
+    if (!request)
+    {
+        return nullptr;
+    }
 
     return JniUtils::convertQueryParamsMapToJavaMap(env, request->getQueryParameters());
 }
@@ -150,7 +157,10 @@ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestHandle
 {
     LOGD("OcResourceRequest_getRequestHandlerFlagNative");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return -1;
+    if (!request)
+    {
+        return -1;
+    }
 
     return static_cast<jint>(request->getRequestHandlerFlag());
 }
@@ -165,10 +175,16 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceRe
 {
     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,
@@ -192,8 +208,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getObservatio
 {
     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,
@@ -222,8 +240,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceRequest_setResourceUri
         return;
     }
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return;
-
+    if (!request)
+    {
+        return;
+    }
     request->setResourceUri(env->GetStringUTFChars(jUri, 0));
 }
 
@@ -237,8 +257,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceUr
 {
     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());
 }
@@ -253,8 +275,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getHeaderOpti
 {
     LOGD("OcResourceRequest_getHeaderOptions");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
-
+    if (!request)
+    {
+        return nullptr;
+    }
     return JniUtils::convertHeaderOptionsVectorToJavaList(env, request->getHeaderOptions());
 }
 
@@ -268,7 +292,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getRequestHan
 {
     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);
@@ -292,7 +319,10 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcResourceRequest_getResourceHa
 {
     LOGD("OcResourceRequest_getResourceHandle");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
-    if (!request) return nullptr;
+    if (!request)
+    {
+        return nullptr;
+    }
 
     JniOcResourceHandle* jniHandle = new JniOcResourceHandle(
         request->getResourceHandle());
@@ -318,4 +348,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceRequest_dispose
     LOGD("OcResourceRequest_dispose");
     JniOcResourceRequest *request = JniOcResourceRequest::getJniOcResourceRequestPtr(env, thiz);
     delete request;
-}
\ No newline at end of file
+}
index 0781d9f..8189073 100644 (file)
@@ -30,10 +30,13 @@ using namespace OC;
 
 JniOcResourceResponse::JniOcResourceResponse
 (std::shared_ptr<OCResourceResponse> resourceResponse)
-: m_response(resourceResponse){}
+: m_response(resourceResponse)
+{
+}
 
 JniOcResourceResponse::~JniOcResourceResponse()
-{}
+{
+}
 
 void JniOcResourceResponse::setErrorCode(const int eCode)
 {
@@ -111,8 +114,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setErrorCode
 {
     LOGD("OcResourceResponse_setErrorCode");
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     response->setErrorCode(static_cast<int>(eCode));
 }
 
@@ -126,8 +131,10 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceResponse_getNewResour
 {
     LOGD("OcResourceResponse_getNewResourceUri");
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return nullptr;
-
+    if (!response)
+    {
+        return nullptr;
+    }
     return env->NewStringUTF(response->getNewResourceUri().c_str());
 }
 
@@ -141,8 +148,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setNewResourceU
 {
     LOGD("OcResourceResponse_setNewResourceUri");
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     response->setNewResourceUri(env->GetStringUTFChars(jstr, 0));
 }
 
@@ -161,8 +170,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setHeaderOption
         return;
     }
     JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!jniResponse) return;
-
+    if (!jniResponse)
+    {
+        return;
+    }
     HeaderOptions headerOptions;
     JniUtils::convertJavaHeaderOptionsArrToVector(env, jHeaderOptions, headerOptions);
 
@@ -184,11 +195,15 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setRequestHandl
         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());
 }
 
@@ -207,11 +222,15 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceHand
         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());
 }
 
@@ -225,8 +244,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResponseResu
 {
     LOGD("OcResourceResponse_setResponseResult");
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     response->setResponseResult(JniUtils::getOCEntityHandlerResult(env, static_cast<int>(responseResult)));
 }
 
@@ -252,12 +273,16 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepr
 
     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));
 }
 
@@ -276,8 +301,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepr
         return;
     }
     JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
-    if (!response) return;
-
+    if (!response)
+    {
+        return;
+    }
     OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
         jRepresentation);
 
@@ -317,4 +344,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_dispose
     LOGD("OcResourceResponse_dispose");
     JniOcResourceResponse *resp = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
     delete resp;
-}
\ No newline at end of file
+}
index 77c8dc6..7585b7b 100644 (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()
 {
@@ -240,6 +242,89 @@ OCStackResult JniOcSecureResource::provisionACL(JNIEnv* env, jobject _acl, jobje
     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)
 {
@@ -543,6 +628,55 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionPairwise
 
 /*
  * 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;
  */
index 0b98f75..d071e96 100644 (file)
@@ -55,7 +55,8 @@ class JniOcSecureResource
                 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;
@@ -118,6 +119,14 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionPairwise
 
 /*
  * 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;
  */
index c5c3d7d..e2c6175 100644 (file)
 #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;
@@ -62,6 +74,8 @@ jclass g_cls_OcResourceIdentifier = 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;
@@ -94,6 +108,8 @@ jmethodID g_mid_OcPresenceStatus_get = 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;
@@ -103,6 +119,12 @@ jmethodID g_mid_OcOicSecAcl_get_periods_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)
@@ -141,7 +163,7 @@ void throwOcException(JNIEnv* env, jobject ex)
 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)
@@ -149,316 +171,353 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
         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;
 }
@@ -474,6 +533,7 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
         return;
     }
 
+
     env->DeleteGlobalRef(g_cls_Integer);
     env->DeleteGlobalRef(g_cls_int1DArray);
     env->DeleteGlobalRef(g_cls_int2DArray);
@@ -509,4 +569,4 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
     env->DeleteGlobalRef(g_cls_OcSecureResource);
     env->DeleteGlobalRef(g_cls_OcProvisionResult);
     env->DeleteGlobalRef(g_cls_OcOicSecAcl);
-}
\ No newline at end of file
+}
index b9f2ccd..7f7e851 100644 (file)
@@ -82,6 +82,8 @@ extern jclass g_cls_OcResourceIdentifier;
 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;
@@ -114,6 +116,8 @@ extern jmethodID g_mid_OcPresenceStatus_get;
 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;
@@ -122,6 +126,12 @@ extern jmethodID g_mid_OcOicSecAcl_get_periods_cnt;
 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);
 
@@ -151,26 +161,29 @@ static JNIEnv* GetJNIEnv(jint& ret)
     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)
@@ -179,4 +192,4 @@ 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
diff --git a/android/android_api/base/jni/JniOnDPDevicesFoundListener.cpp b/android/android_api/base/jni/JniOnDPDevicesFoundListener.cpp
new file mode 100644 (file)
index 0000000..13db923
--- /dev/null
@@ -0,0 +1,190 @@
+/*
+* //******************************************************************
+* //
+* // 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);
+    }
+}
diff --git a/android/android_api/base/jni/JniOnDPDevicesFoundListener.h b/android/android_api/base/jni/JniOnDPDevicesFoundListener.h
new file mode 100644 (file)
index 0000000..88acb61
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+* //******************************************************************
+* //
+* // 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
index 87ebd71..4f95a4c 100644 (file)
@@ -34,35 +34,49 @@ JniOnDeleteListener::~JniOnDeleteListener()
 {
     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;
     }
 
@@ -72,14 +86,20 @@ void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, c
         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);
@@ -90,7 +110,10 @@ void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, c
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -98,14 +121,20 @@ void JniOnDeleteListener::onDeleteCallback(const HeaderOptions& headerOptions, c
         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)
@@ -121,4 +150,4 @@ void JniOnDeleteListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnDeleteListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 28d8e44..520cdfd 100644 (file)
@@ -34,29 +34,41 @@ JniOnDeviceInfoListener::~JniOnDeviceInfoListener()
     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;
     }
 
@@ -68,7 +80,10 @@ void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& oc
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -77,7 +92,10 @@ void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& oc
     {
         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");
@@ -85,7 +103,10 @@ void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& oc
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -97,7 +118,10 @@ void JniOnDeviceInfoListener::foundDeviceCallback(const OC::OCRepresentation& oc
         checkExAndRemoveListener(env);
     }
 
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnDeviceInfoListener::checkExAndRemoveListener(JNIEnv* env)
@@ -113,4 +137,4 @@ void JniOnDeviceInfoListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_removeListenerCallback(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
diff --git a/android/android_api/base/jni/JniOnDirectPairingListener.cpp b/android/android_api/base/jni/JniOnDirectPairingListener.cpp
new file mode 100644 (file)
index 0000000..085c2b9
--- /dev/null
@@ -0,0 +1,159 @@
+/*
+* //******************************************************************
+* //
+* // 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);
+    }
+}
diff --git a/android/android_api/base/jni/JniOnDirectPairingListener.h b/android/android_api/base/jni/JniOnDirectPairingListener.h
new file mode 100644 (file)
index 0000000..8ec2b7e
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+* //******************************************************************
+* //
+* // 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
index 2bc8624..1a46903 100644 (file)
@@ -35,29 +35,41 @@ JniOnGetListener::~JniOnGetListener()
     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);
@@ -65,7 +77,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == envRet)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -75,14 +90,20 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
         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);
@@ -93,7 +114,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -105,7 +129,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -115,7 +142,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
         {
             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);
@@ -127,7 +157,10 @@ void JniOnGetListener::onGetCallback(const HeaderOptions& headerOptions,
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnGetListener::checkExAndRemoveListener(JNIEnv* env)
@@ -143,4 +176,4 @@ void JniOnGetListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnGetListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 3ad1d11..03d92f0 100644 (file)
@@ -34,36 +34,51 @@ JniOnObserveListener::~JniOnObserveListener()
 {
     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;
     }
 
@@ -73,14 +88,20 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         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);
@@ -91,7 +112,10 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -103,7 +127,10 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -112,7 +139,10 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -134,7 +164,10 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
         }
     }
 
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnObserveListener::checkExAndRemoveListener(JNIEnv* env)
@@ -150,4 +183,4 @@ void JniOnObserveListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnObserveListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 03e2ed8..7a220bf 100644 (file)
@@ -34,29 +34,41 @@ JniOnPlatformInfoListener::~JniOnPlatformInfoListener()
     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;
     }
 
@@ -68,7 +80,10 @@ void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -77,7 +92,10 @@ void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation
     {
         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");
@@ -85,7 +103,10 @@ void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation
     {
         delete rep;
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -97,7 +118,10 @@ void JniOnPlatformInfoListener::foundPlatformCallback(const OC::OCRepresentation
         checkExAndRemoveListener(env);
     }
 
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnPlatformInfoListener::checkExAndRemoveListener(JNIEnv* env)
index 575748e..6a9bb06 100644 (file)
@@ -34,36 +34,51 @@ JniOnPostListener::~JniOnPostListener()
 {
     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;
     }
 
@@ -73,14 +88,20 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
         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);
@@ -91,7 +112,10 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -103,7 +127,10 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -112,7 +139,10 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -125,7 +155,10 @@ void JniOnPostListener::onPostCallback(const HeaderOptions& headerOptions,
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnPostListener::checkExAndRemoveListener(JNIEnv* env)
@@ -141,4 +174,4 @@ void JniOnPostListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnPostListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 023c61d..9223250 100644 (file)
@@ -34,14 +34,20 @@ JniOnPresenceListener::~JniOnPresenceListener()
     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();
+        }
     }
 }
 
@@ -49,17 +55,26 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     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;
     }
 
@@ -67,7 +82,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     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;
     }
 
@@ -76,7 +94,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     if (!jPresenceStatus)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -84,7 +105,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     if (!jListener)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -92,7 +116,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     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",
@@ -100,7 +127,10 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
     if (!midL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -111,7 +141,11 @@ void JniOnPresenceListener::onPresenceCallback(OCStackResult result, const unsig
         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)
@@ -132,4 +166,4 @@ void JniOnPresenceListener::checkExAndRemoveListener(JNIEnv* env)
 jweak JniOnPresenceListener::getJWListener()
 {
     return this->m_jwListener;
-}
\ No newline at end of file
+}
index 7f375b9..961280a 100644 (file)
@@ -34,36 +34,51 @@ JniOnPutListener::~JniOnPutListener()
 {
     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;
     }
 
@@ -73,14 +88,20 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
         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);
@@ -91,7 +112,10 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
         if (!jHeaderOptionList)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -103,7 +127,10 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
         {
             delete rep;
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -113,7 +140,10 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
         if (!midL)
         {
             checkExAndRemoveListener(env);
-            if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+            if (JNI_EDETACHED == envRet)
+            {
+                g_jvm->DetachCurrentThread();
+            }
             return;
         }
 
@@ -126,7 +156,10 @@ void JniOnPutListener::onPutCallback(const HeaderOptions& headerOptions,
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == envRet)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniOnPutListener::checkExAndRemoveListener(JNIEnv* env)
@@ -142,4 +175,4 @@ void JniOnPutListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_ownerResource->removeOnPutListener(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index cdc68d3..270b3f8 100644 (file)
@@ -34,35 +34,48 @@ JniOnResourceFoundListener::~JniOnResourceFoundListener()
     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);
@@ -71,24 +84,30 @@ void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCRes
     {
         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())
@@ -96,11 +115,16 @@ void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCRes
         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)
@@ -116,4 +140,4 @@ void JniOnResourceFoundListener::checkExAndRemoveListener(JNIEnv* env)
     {
         m_removeListenerCallback(env, m_jwListener);
     }
-}
\ No newline at end of file
+}
index 55cdfba..12377d1 100644 (file)
@@ -32,40 +32,57 @@ JniPinCheckListener::~JniPinCheckListener()
     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;
     }
 
@@ -73,5 +90,8 @@ void JniPinCheckListener::PinCallback(char *pinBuf, size_t bufSize)
     OICStrcpy(pinBuf, bufSize, str);
     env->ReleaseStringUTFChars(jpin, str);
 
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
index 6b9fd04..066a677 100644 (file)
@@ -35,26 +35,38 @@ JniProvisionResultListner::~JniProvisionResultListner()
     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;
     }
 
@@ -63,7 +75,10 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
     if (!clsL)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -72,7 +87,10 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
     if (!jResultList)
     {
         checkExAndRemoveListener(env);
-        if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+        if (JNI_EDETACHED == ret)
+        {
+            g_jvm->DetachCurrentThread();
+        }
         return;
     }
 
@@ -109,10 +127,19 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
             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;
     }
@@ -121,7 +148,10 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
     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);
@@ -131,7 +161,10 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
     }
 
     checkExAndRemoveListener(env);
-    if (JNI_EDETACHED == ret) g_jvm->DetachCurrentThread();
+    if (JNI_EDETACHED == ret)
+    {
+        g_jvm->DetachCurrentThread();
+    }
 }
 
 void JniProvisionResultListner::checkExAndRemoveListener(JNIEnv* env)
index 6df56d7..8bf5242 100644 (file)
@@ -35,7 +35,8 @@ enum class ListenerFunc
     PROVISIONCREDENTIALS,
     UNLINKDEVICES,
     REMOVEDEVICE,
-    PROVISIONPAIRWISEDEVICES
+    PROVISIONPAIRWISEDEVICES,
+    PROVISIONDIRECTPAIRING
 };
 
 class JniProvisionResultListner
index 24e4f57..8198e49 100644 (file)
@@ -232,3 +232,89 @@ OCStackResult JniSecureUtils::convertJavaACLToOCAcl(JNIEnv *env, jobject in, Oic
 
     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;
+}
index c239c44..c7226a5 100644 (file)
@@ -35,4 +35,5 @@ class JniSecureUtils
                 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);
 };
index 4e3f276..3ee3ada 100644 (file)
 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;
@@ -40,15 +49,24 @@ jobject JniUtils::convertStrVectorToJavaStrList(JNIEnv *env, std::vector<std::st
 
 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);
     }
 }
@@ -56,12 +74,19 @@ void JniUtils::convertJavaStrArrToStrVector(JNIEnv *env, jobjectArray jStrArr, s
 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(
@@ -70,7 +95,10 @@ void JniUtils::convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHe
 
         headerOptions.push_back(hopt);
 
-        if (env->ExceptionCheck()) return;
+        if (env->ExceptionCheck())
+        {
+            return;
+        }
         env->DeleteLocalRef(header);
         env->DeleteLocalRef(jData);
     }
@@ -79,7 +107,10 @@ void JniUtils::convertJavaHeaderOptionsArrToVector(JNIEnv *env, jobjectArray jHe
 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)
     {
@@ -89,10 +120,16 @@ jobject JniUtils::convertHeaderOptionsVectorToJavaList(JNIEnv *env, const OC::He
             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);
     }
 
@@ -101,25 +138,43 @@ jobject JniUtils::convertHeaderOptionsVectorToJavaList(JNIEnv *env, const OC::He
 
 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);
@@ -129,7 +184,10 @@ void JniUtils::convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap, OC::
 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)
     {
@@ -140,7 +198,10 @@ jobject JniUtils::convertQueryParamsMapToJavaMap(JNIEnv *env, const OC::QueryPar
             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;
@@ -150,16 +211,25 @@ void JniUtils::convertJavaRepresentationArrToVector(JNIEnv *env,
     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);
     }
 }
@@ -169,7 +239,10 @@ jobjectArray JniUtils::convertRepresentationVectorToJavaArray(JNIEnv *env,
 {
     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]);
@@ -182,9 +255,12 @@ jobjectArray JniUtils::convertRepresentationVectorToJavaArray(JNIEnv *env,
             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
+}
index fcfa2a1..a7a259a 100644 (file)
@@ -47,84 +47,89 @@ public:
 
     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;
         };
     }
 
@@ -132,106 +137,106 @@ public:
     {
         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 "";
         }
     }
 };
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcDirectPairDevice.java b/android/android_api/base/src/main/java/org/iotivity/base/OcDirectPairDevice.java
new file mode 100644 (file)
index 0000000..aff3238
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+    }
+}
index e37838d..fc69e48 100644 (file)
@@ -901,6 +901,81 @@ public final class OcPlatform {
             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
      */
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OcPrmType.java b/android/android_api/base/src/main/java/org/iotivity/base/OcPrmType.java
new file mode 100755 (executable)
index 0000000..2c2b37f
--- /dev/null
@@ -0,0 +1,58 @@
+/*\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
index 368eda9..f69b548 100644 (file)
@@ -131,6 +131,46 @@ public class OcSecureResource {
             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.
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/OicSecPdAcl.java b/android/android_api/base/src/main/java/org/iotivity/base/OicSecPdAcl.java
new file mode 100644 (file)
index 0000000..5768123
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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);
+    }
+}
index 57b8738..e06d574 100644 (file)
@@ -31,7 +31,9 @@ public class CaBtPairingInterface {
     private static Context mContext;
 
     private CaBtPairingInterface(Context context) {
-        mContext = context;
+        synchronized(CaBtPairingInterface.class) {
+            mContext = context;
+        }
         registerIntentFilter();
     }
 
index a24e1f3..aaf8bc6 100644 (file)
@@ -32,7 +32,9 @@ public class CaEdrInterface {
     private static Context mContext;
 
     private CaEdrInterface(Context context) {
-        mContext = context;
+        synchronized(CaEdrInterface.class) {
+            mContext = context;
+        }
         registerIntentFilter();
     }
 
index 2314df9..a747953 100644 (file)
@@ -53,7 +53,9 @@ public class CaIpInterface {
     }\r
 \r
     private CaIpInterface(Context context) {\r
-        mContext = context;\r
+        synchronized(CaIpInterface.class) {\r
+            mContext = context;\r
+        }\r
         registerIpStateReceiver();\r
     }\r
 \r
index 0aac643..695359b 100644 (file)
@@ -47,10 +47,14 @@ public class CaLeClientInterface {
     private CaLeClientInterface(Context context) {
         caLeRegisterLeScanCallback(mLeScanCallback);
         caLeRegisterGattCallback(mGattCallback);
-        mContext = context;
+        synchronized(CaLeClientInterface.class) {
+            mContext = context;
+        }
         registerIntentFilter();
     }
 
+
+
     public static void getLeScanCallback() {
         caLeRegisterLeScanCallback(mLeScanCallback);
     }
index ebb273b..dee2ac1 100644 (file)
@@ -49,7 +49,9 @@ public class CaNfcInterface implements NfcAdapter.CreateNdefMessageCallback {
 
     private CaNfcInterface(Context context, Activity activity) {
         Log.d(MYTAG, "NFC  registerNfcReceiver");
-        mContext = context;
+        synchronized(CaNfcInterface.class) {
+            mContext = context;
+        }
         mActivity = activity;
 
         mAdapter = NfcAdapter.getDefaultAdapter(mContext);
diff --git a/android/examples/DirectPairing/.classpath b/android/examples/DirectPairing/.classpath
new file mode 100644 (file)
index 0000000..26bdfa6
--- /dev/null
@@ -0,0 +1,9 @@
+<?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
diff --git a/android/examples/DirectPairing/.project b/android/examples/DirectPairing/.project
new file mode 100644 (file)
index 0000000..2dadd42
--- /dev/null
@@ -0,0 +1,33 @@
+<?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
diff --git a/android/examples/DirectPairing/DirectPairing.iml b/android/examples/DirectPairing/DirectPairing.iml
new file mode 100644 (file)
index 0000000..5de258a
--- /dev/null
@@ -0,0 +1,96 @@
+<?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>
diff --git a/android/examples/DirectPairing/build.gradle b/android/examples/DirectPairing/build.gradle
new file mode 100644 (file)
index 0000000..8499e31
--- /dev/null
@@ -0,0 +1,38 @@
+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
diff --git a/android/examples/DirectPairing/project.properties b/android/examples/DirectPairing/project.properties
new file mode 100644 (file)
index 0000000..8e02666
--- /dev/null
@@ -0,0 +1,15 @@
+# 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
diff --git a/android/examples/DirectPairing/src/main/AndroidManifest.xml b/android/examples/DirectPairing/src/main/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..54ec6b9
--- /dev/null
@@ -0,0 +1,29 @@
+<?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>
diff --git a/android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat b/android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat
new file mode 100644 (file)
index 0000000..43b7a1c
Binary files /dev/null and b/android/examples/DirectPairing/src/main/assets/oic_svr_db_client_directpairing.dat differ
diff --git a/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/ExpandableListAdapter.java b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/ExpandableListAdapter.java
new file mode 100644 (file)
index 0000000..377917c
--- /dev/null
@@ -0,0 +1,137 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+    }
+
+}
diff --git a/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/Led.java b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/Led.java
new file mode 100644 (file)
index 0000000..f44f97c
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+    }
+}
diff --git a/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/MainActivity.java b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/MainActivity.java
new file mode 100644 (file)
index 0000000..90c4301
--- /dev/null
@@ -0,0 +1,534 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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());
+                }
+            }
+        }
+
+    }
+}
diff --git a/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/StringConstants.java b/android/examples/DirectPairing/src/main/java/org/iotivity/base/examples/DirectPairing/StringConstants.java
new file mode 100644 (file)
index 0000000..c793422
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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;
+}
diff --git a/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png
new file mode 100644 (file)
index 0000000..2e69816
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_down.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png
new file mode 100644 (file)
index 0000000..91667d5
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-hdpi/arrow_right.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png b/android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..288b665
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-hdpi/ic_launcher.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png b/android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..6ae570b
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-mdpi/ic_launcher.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png b/android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..d4fb7cd
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-xhdpi/ic_launcher.png differ
diff --git a/android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png b/android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..85a6081
Binary files /dev/null and b/android/examples/DirectPairing/src/main/res/drawable-xxhdpi/ic_launcher.png differ
diff --git a/android/examples/DirectPairing/src/main/res/layout/activity_main.xml b/android/examples/DirectPairing/src/main/res/layout/activity_main.xml
new file mode 100644 (file)
index 0000000..1ee1a2b
--- /dev/null
@@ -0,0 +1,95 @@
+<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
diff --git a/android/examples/DirectPairing/src/main/res/layout/custom_list_view.xml b/android/examples/DirectPairing/src/main/res/layout/custom_list_view.xml
new file mode 100644 (file)
index 0000000..74874c5
--- /dev/null
@@ -0,0 +1,34 @@
+<?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
diff --git a/android/examples/DirectPairing/src/main/res/layout/group_indicator.xml b/android/examples/DirectPairing/src/main/res/layout/group_indicator.xml
new file mode 100644 (file)
index 0000000..95be916
--- /dev/null
@@ -0,0 +1,6 @@
+<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
diff --git a/android/examples/DirectPairing/src/main/res/layout/list_group.xml b/android/examples/DirectPairing/src/main/res/layout/list_group.xml
new file mode 100644 (file)
index 0000000..d4d9218
--- /dev/null
@@ -0,0 +1,28 @@
+<?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
diff --git a/android/examples/DirectPairing/src/main/res/layout/list_item.xml b/android/examples/DirectPairing/src/main/res/layout/list_item.xml
new file mode 100644 (file)
index 0000000..6579c36
--- /dev/null
@@ -0,0 +1,39 @@
+<?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
diff --git a/android/examples/DirectPairing/src/main/res/menu/main.xml b/android/examples/DirectPairing/src/main/res/menu/main.xml
new file mode 100644 (file)
index 0000000..3e5155b
--- /dev/null
@@ -0,0 +1,11 @@
+<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
diff --git a/android/examples/DirectPairing/src/main/res/values-v11/styles.xml b/android/examples/DirectPairing/src/main/res/values-v11/styles.xml
new file mode 100644 (file)
index 0000000..0ce1396
--- /dev/null
@@ -0,0 +1,11 @@
+<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
diff --git a/android/examples/DirectPairing/src/main/res/values-v14/styles.xml b/android/examples/DirectPairing/src/main/res/values-v14/styles.xml
new file mode 100644 (file)
index 0000000..94dd245
--- /dev/null
@@ -0,0 +1,12 @@
+<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
diff --git a/android/examples/DirectPairing/src/main/res/values-w820dp/dimens.xml b/android/examples/DirectPairing/src/main/res/values-w820dp/dimens.xml
new file mode 100644 (file)
index 0000000..f9f069f
--- /dev/null
@@ -0,0 +1,10 @@
+<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
diff --git a/android/examples/DirectPairing/src/main/res/values/dimens.xml b/android/examples/DirectPairing/src/main/res/values/dimens.xml
new file mode 100644 (file)
index 0000000..2e0e2ae
--- /dev/null
@@ -0,0 +1,7 @@
+<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
diff --git a/android/examples/DirectPairing/src/main/res/values/strings.xml b/android/examples/DirectPairing/src/main/res/values/strings.xml
new file mode 100644 (file)
index 0000000..0fe7671
--- /dev/null
@@ -0,0 +1,10 @@
+<?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
diff --git a/android/examples/DirectPairing/src/main/res/values/styles.xml b/android/examples/DirectPairing/src/main/res/values/styles.xml
new file mode 100644 (file)
index 0000000..287aa96
--- /dev/null
@@ -0,0 +1,20 @@
+<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
index fbd8eda..db828b5 100644 (file)
@@ -24,6 +24,8 @@ import org.iotivity.base.OcPlatform;
 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;
@@ -59,6 +61,22 @@ public class ProvisioningClient extends Activity implements
     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
@@ -123,7 +141,7 @@ public class ProvisioningClient extends Activity implements
         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
@@ -188,6 +206,32 @@ public class ProvisioningClient extends Activity implements
         }
     }
 
+
+    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()
@@ -544,11 +588,11 @@ public class ProvisioningClient extends Activity implements
                 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 {
@@ -568,6 +612,12 @@ public class ProvisioningClient extends Activity implements
 
         @Override
         protected void onPostExecute(String s) {
+
+
+            if (ownedDeviceList.size() > 0 && "success".equals(s)) {
+                doDPProvisioning();
+            }
+
             if (ownedDeviceList.size() > 1 && "success".equals(s)) {
                 doPairwiseProvisioning();
             }
index cde94ab..3d6612a 100755 (executable)
@@ -1,5 +1,5 @@
 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'
 }
index d1f1a07..38a4c8b 100644 (file)
@@ -15,8 +15,8 @@ host_target_map = {
 
 # 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'],
index 472ce12..684370b 100644 (file)
@@ -88,8 +88,9 @@ protected:
     WrapRequest *m_typeRequest;
 };
 
-struct WrapRequest
+class WrapRequest
 {
+public:
     WrapRequest(WrapResource *wres, RequestType type, token_t token);
 
     friend class WrapResource;
index 84db1fa..8caa729 100644 (file)
@@ -140,12 +140,13 @@ OCStackResult SetDeviceInfo()
         {
             .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);
 }
 
index aa77eb0..6c166b1 100644 (file)
@@ -237,13 +237,14 @@ ca_cond ca_cond_new(void)
         }
 
  #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!",
@@ -428,7 +429,8 @@ CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseco
         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
index 722a1c0..05e7601 100644 (file)
@@ -141,6 +141,13 @@ void CATCPStopServer();
 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.
index 5163939..6ca39de 100644 (file)
@@ -560,14 +560,14 @@ static int32_t CAHandleSecureEvent(dtls_context_t *context,
             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);
     }
 
index bdcc44e..6a674ae 100644 (file)
@@ -210,7 +210,7 @@ CAResult_t CAEDRGetAdapterEnableState(bool *state)
         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)
     {
@@ -249,7 +249,7 @@ void CAEDRJniInitContext()
 
 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)
@@ -353,7 +353,7 @@ CAResult_t CAEDRInitialize()
     }
 
     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)
     {
@@ -404,7 +404,7 @@ void CAEDRTerminate()
     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)
     {
@@ -451,7 +451,7 @@ CAResult_t CAEDRDestroyJniInterface()
     }
 
     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)
     {
@@ -531,7 +531,7 @@ CAResult_t CAEDRSendMulticastMessage(const uint8_t* data, uint32_t dataLen)
     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)
     {
@@ -572,7 +572,7 @@ CAResult_t CAEDRGetInterfaceInfo(char **address)
 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)
     {
@@ -619,7 +619,7 @@ CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const uint8_t* data,
     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)
     {
index 3d4dcb6..b1cf8a0 100644 (file)
@@ -118,7 +118,7 @@ static void CAReceiveHandler(void *data)
     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)
     {
@@ -172,7 +172,7 @@ static void CAAcceptHandler(void *data)
     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)
     {
@@ -282,7 +282,7 @@ CAResult_t CAEDRServerStop()
     }
 
     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)
     {
@@ -413,7 +413,7 @@ CAResult_t CAEDRServerInitialize(ca_thread_pool_t handle)
 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)
     {
@@ -477,7 +477,7 @@ void CAEDRServerTerminate()
         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)
     {
index 7f36db3..c229b68 100644 (file)
@@ -72,14 +72,14 @@ CAResult_t CAEDRStartNetworkMonitor()
     {
         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");
index 199f884..62b4fdc 100644 (file)
@@ -160,7 +160,7 @@ static void CALEScanThread(void* object)
     (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)
     {
@@ -301,7 +301,7 @@ CAResult_t CALECreateJniInterfaceObject()
     }
 
     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)
     {
@@ -382,7 +382,7 @@ CAResult_t CALEClientInitialize()
     }
 
     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)
     {
@@ -481,7 +481,7 @@ void CALEClientTerminate()
     }
 
     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)
     {
@@ -577,7 +577,7 @@ CAResult_t CALEClientDestroyJniInterface()
     }
 
     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)
     {
@@ -677,7 +677,7 @@ CAResult_t CALEClientSendMulticastMessage(const uint8_t* data,
     }
 
     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)
     {
@@ -842,7 +842,7 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
     }
 
     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)
     {
@@ -970,11 +970,12 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
     }
 
     // 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;
@@ -1298,7 +1299,7 @@ CAResult_t CALEClientStartScan()
     }
 
     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)
     {
@@ -1526,7 +1527,7 @@ CAResult_t CALEClientStopScan()
     }
 
     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)
     {
@@ -2124,7 +2125,7 @@ static void CALEWriteCharacteristicThread(void* object)
     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)
     {
@@ -2585,7 +2586,7 @@ CAResult_t CALEClientCreateUUIDList()
     }
 
     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)
     {
@@ -4005,7 +4006,7 @@ void CAStopLEGattClient()
     }
 
     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)
     {
@@ -4165,39 +4166,6 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeScanCallback(JNIEnv *env, jobject o
     }
 }
 
-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
@@ -4233,13 +4201,14 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
     }
     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)
             {
@@ -4271,7 +4240,9 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattConnectionStateChangeCallback(J
     {
         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)
         {
index 2578f88..4a65ed2 100644 (file)
@@ -158,7 +158,7 @@ CAResult_t CAGetLEAdapterState()
     }
 
     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)
     {
index c25157a..ec1555f 100644 (file)
@@ -103,7 +103,7 @@ CAResult_t CALEServerCreateJniInterfaceObject()
     }
 
     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)
     {
@@ -407,7 +407,7 @@ CAResult_t CALEStartAdvertise()
     }
 
     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)
     {
@@ -1453,7 +1453,7 @@ CAResult_t CALEServerInitialize()
     }
 
     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)
     {
@@ -1530,7 +1530,7 @@ void CALEServerTerminate()
     }
 
     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)
     {
@@ -1586,7 +1586,7 @@ CAResult_t CALEServerSendUnicastMessage(const char* address, const uint8_t* data
     }
 
     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)
     {
@@ -1627,7 +1627,7 @@ CAResult_t CALEServerSendMulticastMessage(const uint8_t* data, uint32_t dataLen)
     }
 
     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)
     {
@@ -1679,7 +1679,7 @@ CAResult_t CALEServerStartMulticastServer()
     }
 
     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)
     {
@@ -1741,7 +1741,7 @@ CAResult_t CALEServerStopMulticastServer()
     }
 
     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)
     {
@@ -2473,7 +2473,7 @@ CAResult_t CAStopLEGattServer()
     }
 
     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)
     {
index a78aa06..a6a9cf5 100644 (file)
@@ -346,6 +346,16 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             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;
@@ -483,23 +493,20 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
                 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:
@@ -578,6 +585,21 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
     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)
 {
@@ -619,9 +641,18 @@ CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
     }
     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;
         }
@@ -782,6 +813,44 @@ CAResult_t CAReceiveLastBlock(const CABlockDataID_t *blockID, const CAData_t *re
     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,
@@ -806,39 +875,15 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         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)
@@ -886,15 +931,8 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         {
             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
@@ -979,39 +1017,15 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         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)
     {
@@ -2042,6 +2056,7 @@ CAData_t* CACreateNewDataSet(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint
 
         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.
@@ -2205,8 +2220,7 @@ CAResult_t CAHandleBlockErrorResponse(coap_block_t *block, uint16_t blockType,
     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");
@@ -2333,93 +2347,35 @@ CAResult_t CACheckBlockDataValidation(const CAData_t *sendData, CABlockData_t **
     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;
 }
index 82919b7..7355e2a 100644 (file)
@@ -100,7 +100,7 @@ CAResult_t CAStartListeningServer()
 {
     OIC_LOG(DEBUG, TAG, "CAStartListeningServer");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -112,7 +112,7 @@ CAResult_t CAStopListeningServer()
 {
     OIC_LOG(DEBUG, TAG, "CAStopListeningServer");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -124,7 +124,7 @@ CAResult_t CAStartDiscoveryServer()
 {
     OIC_LOG(DEBUG, TAG, "CAStartDiscoveryServer");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -137,7 +137,7 @@ void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHand
 {
     OIC_LOG(DEBUG, TAG, "CARegisterHandler");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         OIC_LOG(DEBUG, TAG, "CA is not initialized");
         return;
@@ -151,7 +151,7 @@ CAResult_t CARegisterDTLSHandshakeCallback(CAErrorCallback dtlsHandshakeCallback
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSHandshakeCallback");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -165,7 +165,7 @@ CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDT
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -180,7 +180,7 @@ CAResult_t CARegisterDTLSX509CredentialsHandler(CAGetDTLSX509CredentialsHandler
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSX509CredentialsHandler");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -193,7 +193,7 @@ CAResult_t CARegisterDTLSCrlHandler(CAGetDTLSCrlHandler GetDTLSCrlHandler)
 {
     OIC_LOG(DEBUG, TAG, "CARegisterDTLSCrlHandler");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -251,7 +251,7 @@ CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size)
 {
     OIC_LOG(DEBUG, TAG, "CAGetNetworkInformation");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -306,7 +306,7 @@ CAResult_t CASendRequest(const CAEndpoint_t *object, const CARequestInfo_t *requ
 {
     OIC_LOG(DEBUG, TAG, "CASendRequest");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -326,7 +326,7 @@ CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *re
 {
     OIC_LOG(DEBUG, TAG, "CASendResponse");
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -346,7 +346,7 @@ CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork)
 {
     OIC_LOG_V(DEBUG, TAG, "Selected network : %d", interestedNetwork);
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
@@ -402,7 +402,7 @@ CAResult_t CAUnSelectNetwork(CATransportAdapter_t nonInterestedNetwork)
 {
     OIC_LOG_V(DEBUG, TAG, "unselected network : %d", nonInterestedNetwork);
 
-    if(!g_isInitialized)
+    if (!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
index 7ae093c..5de93f1 100644 (file)
@@ -75,7 +75,7 @@ static int CAGetAdapterIndex(CATransportAdapter_t cType)
 
 static void CARegisterCallback(CAConnectivityHandler_t handler)
 {
-    if(handler.startAdapter == NULL ||
+    if (handler.startAdapter == NULL ||
         handler.startListenServer == NULL ||
         handler.stopListenServer == NULL ||
         handler.startDiscoveryServer == NULL ||
@@ -438,7 +438,7 @@ CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, u
     {
         void* ptrType = u_arraylist_get(list, i);
 
-        if(NULL == ptrType)
+        if (NULL == ptrType)
         {
             continue;
         }
@@ -451,9 +451,8 @@ CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, u
 
         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;
         }
 
index a9d554e..d6c2c55 100644 (file)
@@ -140,9 +140,8 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
     }
 
     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)
@@ -153,7 +152,7 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
             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");
@@ -182,7 +181,7 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
             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");
@@ -415,7 +414,7 @@ static CAResult_t CAProcessMulticastData(const CAData_t *data)
     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)
     {
@@ -520,11 +519,12 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
     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
@@ -903,12 +903,12 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         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;
@@ -917,7 +917,7 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         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);
@@ -983,7 +983,7 @@ CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg
 
 #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));
@@ -997,7 +997,7 @@ CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg
     {
         // 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));
@@ -1251,7 +1251,7 @@ void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
 
 static void CALogPayloadInfo(CAInfo_t *info)
 {
-    if(info)
+    if (info)
     {
         if (info->options)
         {
index 7d84c1c..03eca3b 100644 (file)
@@ -45,7 +45,6 @@
 
 #define TAG "OIC_CA_PRTCL_MSG"
 
-#define CA_BUFSIZE (128)
 #define CA_PDU_MIN_SIZE (4)
 #define CA_ENCODE_BUFFER_SIZE (4)
 
@@ -313,7 +312,7 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
 #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 */
@@ -447,7 +446,7 @@ CAResult_t CAParseUriPartial(const unsigned char *str, size_t length, int target
     }
     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) :
@@ -662,7 +661,7 @@ int CAOrderOpts(void *a, void *b)
 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)))
     {
@@ -747,7 +746,7 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
         }
     }
 
-    coap_opt_t *option;
+    coap_opt_t *option = NULL;
     char optionResult[CA_MAX_URI_LENGTH] = {0};
     uint32_t idx = 0;
     uint32_t optionLength = 0;
@@ -962,17 +961,13 @@ CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
     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;
@@ -1053,7 +1048,9 @@ uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
         // 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';
     }
index 5e62720..3e10065 100644 (file)
@@ -43,7 +43,6 @@ static void CAQueueingThreadBaseRoutine(void *threadValue)
     if (NULL == thread)
     {
         OIC_LOG(ERROR, TAG, "thread data passing error!!");
-
         return;
     }
 
@@ -128,28 +127,30 @@ CAResult_t CAQueueingThreadInitialize(CAQueueingThread_t *thread, ca_thread_pool
     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)
@@ -251,7 +252,7 @@ CAResult_t CAQueueingThreadDestroy(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)
             {
index 5fa0ff3..52482b3 100644 (file)
@@ -68,6 +68,7 @@
 #include "caremotehandler.h"
 #include "caprotocolmessage.h"
 #include "oic_malloc.h"
+#include "ocrandom.h"
 #include "logger.h"
 
 #define TAG "OIC_CA_RETRANS"
@@ -104,11 +105,11 @@ uint64_t getCurrentTimeInMicroSeconds();
  */
 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
 }
index ff70009..0809c8d 100644 (file)
@@ -213,7 +213,6 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
     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;
@@ -245,7 +244,7 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
         }
 
         // 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;
@@ -321,7 +320,7 @@ CAResult_t CAIPJniInit()
         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");
@@ -380,7 +379,7 @@ static CAResult_t CAIPDestroyJniInterface()
     }
 
     bool isAttached = false;
-    JNIEnv* env;
+    JNIEnv* env = NULL;
     jint res = (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
index 022d585..7e9d2cc 100644 (file)
@@ -483,7 +483,7 @@ void CADeInitializeIPGlobals()
 
 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;
index 9247bc3..0b06a1d 100644 (file)
@@ -133,7 +133,7 @@ CAResult_t CANfcCreateJniInterfaceObject()
     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
@@ -243,7 +243,7 @@ CAResult_t CANFCStartServer()
 \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
@@ -531,7 +531,7 @@ CAResult_t CANfcSendDataImpl(const CAEndpoint_t * ep, const char* data, uint32_t
 \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
index 89cda0f..cf72799 100644 (file)
@@ -92,7 +92,7 @@ static void CATCPDestroyCond();
 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);
@@ -216,10 +216,10 @@ static void CAFindReadyMessage()
         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");
 
index d43c6f5..09e7550 100644 (file)
@@ -29,7 +29,8 @@
 
 class CABlockTransferTests : public testing::Test {
     protected:
-    virtual void SetUp() {
+    virtual void SetUp()
+    {
         CAInitialize();
     }
 
index b982b74..0d24bad 100644 (file)
@@ -46,7 +46,7 @@ static const char CLASSPATH_BT_DEVICE[] = "android/bluetooth/BluetoothDevice";
 
 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)
index 12d4e0f..c77ea8f 100644 (file)
@@ -50,7 +50,7 @@ CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char* address)
     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)
     {
@@ -126,7 +126,7 @@ CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char* address)
     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)
     {
index 7e12912..a8d3e9f 100644 (file)
@@ -63,11 +63,12 @@ const OicSecCred_t* GetCredResourceData(const OicUuid_t* subjectId);
  * @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.
index 3ba9e62..7f63d92 100644 (file)
@@ -29,7 +29,6 @@ extern "C" {
 
 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;
index 0cc68a4..10c9e50 100644 (file)
@@ -263,6 +263,13 @@ typedef enum
     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;
@@ -310,6 +317,10 @@ struct OicSecKey
 {
     uint8_t                *data;
     size_t                  len;
+
+    // TODO: This field added as workaround. Will be replaced soon.
+    OicEncodingType_t encoding;
+
 };
 
 /**
index 3588f1a..2fea369 100644 (file)
@@ -33,13 +33,13 @@ provisioning_env.AppendUnique(CPPPATH = [
                '../../../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',
index 91a7619..dc7485d 100644 (file)
@@ -37,6 +37,7 @@
 
 #define MAX_URI_LENGTH (64)
 #define MAX_PERMISSION_LENGTH (5)
+#define MAX_ACL_LENGTH 100
 #define CREATE (1)
 #define READ (2)
 #define UPDATE (4)
@@ -71,7 +72,7 @@ typedef enum
  */
 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++)
@@ -214,7 +215,7 @@ static int InputACL(OicSecAcl_t *acl)
     //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;
index 28fc7d7..66d6cb1 100644 (file)
@@ -19,7 +19,6 @@
 
  ******************************************************************/
 
-#include <oic_malloc.h>
 #include <gtest/gtest.h>
 #include "ckm_info.h"
 
@@ -153,13 +152,13 @@ TEST(CKMInfoTest, SetGetCAPrivateKey)
     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
@@ -168,13 +167,13 @@ TEST(CKMInfoTest, SetGetCAPublicKey)
     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
@@ -183,13 +182,13 @@ TEST(CKMInfoTest, SetGetCAName)
     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
@@ -202,19 +201,20 @@ TEST(CKMInfoTest, SetGetCKMInfo)
     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));
@@ -224,10 +224,6 @@ TEST(CKMInfoTest, SetGetCKMInfo)
     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
@@ -236,13 +232,12 @@ TEST(CKMInfoTest, SetGetCACertificate)
     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
index 99fb37d..b87dd56 100644 (file)
 #include "ocstack.h"
 #include "securevirtualresourcetypes.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
 /**
  * Function to generate credentials according to the type.
  *
index c6769e8..fe4e546 100644 (file)
@@ -41,7 +41,29 @@ extern "C"
  */
 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.
index 986c360..155513e 100644 (file)
@@ -117,6 +117,30 @@ OCStackResult OCProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceIn
                              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
index e1c6d5a..19fd535 100644 (file)
@@ -53,6 +53,8 @@ extern "C"
 #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
@@ -152,6 +154,34 @@ static void provisionAclCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool
     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)
@@ -780,6 +810,125 @@ CKLST_ERROR:
     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
@@ -1215,7 +1364,7 @@ static int waitCallbackRet(void)
 
 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;
     }
@@ -1278,6 +1427,10 @@ static void printMenu(void)
     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");
 
@@ -1396,6 +1549,18 @@ int main()
                 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:
index 44e80a4..5062374 100644 (file)
@@ -44,8 +44,8 @@ OCStackResult PMGeneratePairWiseCredentials(OicSecCredType_t type, size_t keySiz
         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;
@@ -217,7 +217,7 @@ static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, OicSe
 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;
     }
index b5d4bed..ad8133d 100644 (file)
@@ -163,6 +163,36 @@ OCStackResult OCProvisionACL(void* ctx, const OCProvisionDev_t *selectedDeviceIn
 }
 
 /**
+ * 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.
index 92b054f..68d8dc6 100644 (file)
@@ -425,6 +425,28 @@ static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
                 &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)
         {
@@ -959,15 +981,17 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
         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.");
index 618a36b..b72c28c 100644 (file)
@@ -573,7 +573,7 @@ static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle
             // 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.");
@@ -696,6 +696,22 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                     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,
index f77bf05..e3f5bba 100644 (file)
@@ -93,6 +93,16 @@ struct ACLData
     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.
  */
@@ -306,7 +316,9 @@ static OCStackResult provisionCredentials(const OicSecCred_t *cred,
         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);
@@ -543,8 +555,9 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
         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))
     {
@@ -1711,3 +1724,245 @@ error:
     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;
+}
index c632e4c..7c36b06 100644 (file)
@@ -90,6 +90,7 @@ unittest_src = ['pmutilitytest.cpp',
                 'secureresourceprovider.cpp',
                 'provisioningdatabasemanager.cpp',
                 'ocprovisioningmanager.cpp',
+                'credentialgeneratortest.cpp',
                 ]
 
 if target_os not in ['windows']:
diff --git a/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp b/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp
new file mode 100644 (file)
index 0000000..52a034b
--- /dev/null
@@ -0,0 +1,159 @@
+/* *****************************************************************
+ *
+ * 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__
+
index b10129a..ca91b31 100644 (file)
@@ -64,6 +64,18 @@ static void provisioningCB (void* UNUSED1, int UNUSED2, OCProvisionResult_t *UNU
     (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;
@@ -174,3 +186,42 @@ TEST(OCGetLinkedStatusTest, NULLDeviceID)
     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));
+}
index 363f3a6..a55ff93 100644 (file)
@@ -217,7 +217,7 @@ static FILE* fopen_prvnMng(const char* path, const char* mode)
     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);
 }
 
@@ -311,21 +311,21 @@ TEST(InitForOTM, NullParam)
 
     //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
@@ -333,13 +333,13 @@ TEST(InitForOTM, NullParam)
     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;
     }
@@ -354,7 +354,7 @@ TEST(InitForOTM, NullParam)
 
     //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);
 
@@ -421,7 +421,7 @@ TEST(PerformOwnedDeviceDiscovery, NullParam)
         tempDev = tempDev->next;
     }
 
-    EXPECT_EQ(2/*Server*/ + 1/*PT*/, NumOfOwnDevice);
+    EXPECT_EQ(2/*Server*/ , NumOfOwnDevice);
 }
 
 TEST(PerformLinkDevices, NullParam)
index 29b0961..056e8c1 100644 (file)
@@ -484,7 +484,7 @@ FILE* server_fopen(const char *path, const char *mode)
     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);
 }
 
@@ -498,11 +498,11 @@ int main()
     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)
     {
index 05f0f48..c500ec7 100644 (file)
@@ -484,7 +484,7 @@ FILE* server_fopen(const char *path, const char *mode)
     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);
 }
 
@@ -498,11 +498,11 @@ int main()
     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)
     {
index 8d57082..aaa96fb 100644 (file)
@@ -422,7 +422,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
         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.");
@@ -444,7 +444,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                     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.");
@@ -492,7 +492,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                     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.");
@@ -502,7 +502,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                     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);
@@ -539,7 +539,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                                 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;
@@ -603,12 +603,15 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                         // 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);
@@ -618,7 +621,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                             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);
@@ -637,7 +640,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
                                             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);
@@ -678,7 +681,7 @@ OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
             }
 
             // 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);
@@ -886,20 +889,20 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
     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));
 
         /*
@@ -941,8 +944,10 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
             }
         }
     }
+    // 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))
         {
@@ -1091,7 +1096,7 @@ static OCStackResult CreateACLResource()
 
     ret = OCCreateResource(&gAclHandle,
                            OIC_RSRC_TYPE_SEC_ACL,
-                           OIC_MI_DEF,
+                           OC_RSRVD_INTERFACE_DEFAULT,
                            OIC_RSRC_ACL_URI,
                            ACLEntityHandler,
                            NULL,
index be21257..d29187f 100644 (file)
@@ -72,16 +72,6 @@ void DeleteAmaclList(OicSecAmacl_t* amacl)
     }
 }
 
-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)
 {
@@ -269,7 +259,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
     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;
@@ -288,7 +278,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
             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;
@@ -323,7 +313,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
                         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;
@@ -398,7 +388,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
             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);
@@ -411,7 +401,7 @@ OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
         }
 
         // 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);
@@ -551,7 +541,7 @@ static OCStackResult CreateAmaclResource()
 {
     OCStackResult ret = OCCreateResource(&gAmaclHandle,
                                          OIC_RSRC_TYPE_SEC_AMACL,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_AMACL_URI,
                                          AmaclEntityHandler,
                                          NULL,
index 76c2c38..c208d3f 100644 (file)
@@ -226,12 +226,9 @@ OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivit
 {
     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);
index ad37dc9..4430793 100644 (file)
@@ -125,7 +125,7 @@ static size_t OicSecCredCount(const OicSecCred_t *secCred)
 }
 
 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)
     {
@@ -181,7 +181,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
             mapSize++;
         }
 #endif /* __WITH_X509__ */
-        if (cred->privateData.data)
+        if (!secureFlag && cred->privateData.data)
         {
             mapSize++;
         }
@@ -246,7 +246,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
         }
 #endif /*__WITH_X509__*/
         //PrivateData -- Not Mandatory
-        if(cred->privateData.data)
+        if(!secureFlag && cred->privateData.data)
         {
             CborEncoder privateMap;
             const size_t privateMapSize = 2;
@@ -258,20 +258,45 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
             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.");
@@ -333,7 +358,7 @@ exit:
         // 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;
     }
 
@@ -376,7 +401,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
         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.");
@@ -420,7 +445,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
 
                     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);
@@ -436,8 +461,10 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                             //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)
@@ -452,8 +479,10 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                             // 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)
@@ -465,7 +494,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                 {
                                     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);
@@ -478,14 +507,48 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                         // 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))
@@ -507,7 +570,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                 {
                                     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);
@@ -518,7 +581,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                     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);
@@ -564,7 +627,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
             }
 
             //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);
@@ -635,6 +698,28 @@ OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t cr
         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);
@@ -659,7 +744,8 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
     {
         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))
@@ -848,10 +934,35 @@ static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoi
     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");
 
@@ -874,6 +985,7 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
     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)
     {
@@ -1013,6 +1125,34 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
     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;
@@ -1087,7 +1227,7 @@ OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
         switch (ehRequest->method)
         {
             case OC_REST_GET:
-                ret = OC_EH_FORBIDDEN;
+                ret = HandleGetRequest(ehRequest);;
                 break;
             case OC_REST_PUT:
                 ret = HandlePutRequest(ehRequest);
@@ -1115,11 +1255,11 @@ OCStackResult CreateCredResource()
 {
     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)
     {
@@ -1248,15 +1388,42 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
                             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;
                     }
                 }
             }
@@ -1265,7 +1432,6 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
         default:
             {
                 OIC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
-                ret = -1;
             }
             break;
     }
@@ -1298,7 +1464,7 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
     }
 
     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,
@@ -1409,6 +1575,7 @@ OCStackResult SetCredRownerId(const OicUuid_t* newROwner)
     OCStackResult ret = OC_STACK_ERROR;
     uint8_t *cborPayload = NULL;
     size_t size = 0;
+    int secureFlag = 0;
     OicUuid_t prevId = {.id={0}};
 
     if(NULL == newROwner)
@@ -1425,7 +1592,7 @@ OCStackResult SetCredRownerId(const OicUuid_t* 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);
index d9f5caf..23781b7 100644 (file)
@@ -373,7 +373,7 @@ static OCStackResult CreateCRLResource()
 {
     OCStackResult ret = OCCreateResource(&gCrlHandle,
                                          OIC_RSRC_TYPE_SEC_CRL,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_CRL_URI,
                                          CRLEntityHandler,
                                          NULL,
index ccdfbc8..33935a1 100644 (file)
@@ -313,7 +313,7 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
 
         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);
@@ -339,7 +339,7 @@ OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
         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")
@@ -863,11 +863,11 @@ OCStackResult CreateDoxmResource()
 {
     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)
old mode 100755 (executable)
new mode 100644 (file)
index 8fcb6b0..01eccd0
@@ -295,7 +295,7 @@ OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
     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;
@@ -306,7 +306,7 @@ OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
         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");
@@ -655,7 +655,7 @@ OCStackResult CreateDpairingResource()
 
     ret = OCCreateResource(&gDpairHandle,
                            OIC_RSRC_TYPE_SEC_DPAIRING,
-                           OIC_MI_DEF,
+                           OC_RSRVD_INTERFACE_DEFAULT,
                            OIC_RSRC_DPAIRING_URI,
                            DpairingEntityHandler,
                            NULL,
index d2491c4..0026762 100644 (file)
@@ -474,7 +474,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
         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");
@@ -485,7 +485,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
         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");
@@ -503,7 +503,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                 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");
@@ -512,7 +512,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                 }
             }
             //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);
@@ -544,7 +544,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                         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);
@@ -555,7 +555,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                         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 };
@@ -574,7 +574,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                                     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;
@@ -638,15 +638,16 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                             }
 
                             // 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 };
@@ -658,7 +659,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                                 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);
@@ -670,7 +671,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                             }
 
                             // 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 };
@@ -681,7 +682,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
                                 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);
@@ -723,7 +724,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
             }
 
             //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 };
@@ -734,7 +735,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
 
                 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);
@@ -748,7 +749,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
             }
 
             //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);
@@ -759,7 +760,7 @@ OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSec
             }
 
             // 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);
@@ -1008,7 +1009,7 @@ OCStackResult CreatePconfResource()
 
     ret = OCCreateResource(&gPconfHandle,
                            OIC_RSRC_TYPE_SEC_PCONF,
-                           OIC_MI_DEF,
+                           OC_RSRVD_INTERFACE_DEFAULT,
                            OIC_RSRC_PCONF_URI,
                            PconfEntityHandler,
                            NULL,
index 75793c2..317991b 100644 (file)
@@ -460,11 +460,12 @@ static OCEntityHandlerResult HandlePstatPostRequest(const OCEntityHandlerRequest
 {
     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)
     {
index d7b3c77..2b435c8 100644 (file)
 
 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";
 
index a1175aa..9cb7f6b 100644 (file)
@@ -230,7 +230,7 @@ OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
 
             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);
@@ -239,14 +239,14 @@ OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
                 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 };
@@ -258,7 +258,7 @@ OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
                 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);
@@ -414,7 +414,7 @@ static OCStackResult CreateSVCResource()
 {
     OCStackResult ret = OCCreateResource(&gSvcHandle,
                                          OIC_RSRC_TYPE_SEC_SVC,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_SVC_URI,
                                          SVCEntityHandler,
                                          NULL,
index 0bd3f75..96afacc 100644 (file)
@@ -281,7 +281,7 @@ OCStackResult CreateVerResource()
 {
     OCStackResult ret = OCCreateResource(&gVerHandle,
                                          OIC_RSRC_TYPE_SEC_VER,
-                                         OIC_MI_DEF,
+                                         OC_RSRVD_INTERFACE_DEFAULT,
                                          OIC_RSRC_VER_URI,
                                          VerEntityHandler,
                                          NULL,
index 09191cb..f0c4a96 100644 (file)
@@ -201,11 +201,12 @@ static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName
     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");
index 4d04eba..9707000 100644 (file)
@@ -31,22 +31,19 @@ target_os = env.get('TARGET_OS')
 # 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'
                ])
 
index ed5e99a..13fce86 100644 (file)
@@ -52,6 +52,7 @@ OicSecCred_t * getCredList()
 #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");
@@ -66,6 +67,7 @@ OicSecCred_t * getCredList()
     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);
@@ -110,7 +112,7 @@ static void printCred(const OicSecCred_t * cred)
            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);
     }
 }
 
@@ -169,7 +171,8 @@ TEST(CredResourceTest, CredEntityHandlerDeleteTest)
     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);
@@ -219,8 +222,9 @@ TEST(CredResourceTest, CredEntityHandlerDeleteTest)
 
 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)
@@ -228,12 +232,12 @@ TEST(CredResourceTest, CredToCBORPayloadNULL)
         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);
 }
 
@@ -241,9 +245,10 @@ TEST(CredResourceTest, CredToCBORPayloadVALID)
 {
     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);
@@ -260,7 +265,8 @@ TEST(CredResourceTest, CBORPayloadToCredVALID)
 
     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);
 
@@ -271,6 +277,33 @@ TEST(CredResourceTest, CBORPayloadToCredVALID)
     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;
@@ -399,3 +432,19 @@ TEST(CredResourceTest, GetDtlsX509Credentials)
 }
 
 #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));
+}
index ee48b7e..d7f7bae 100644 (file)
@@ -252,7 +252,8 @@ OCStackResult FormOCEntityHandlerRequest(
         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
index a985d67..678618c 100644 (file)
@@ -66,8 +66,8 @@ extern void* defaultDeviceHandlerCallbackParameter;
 /** 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.
index 88eba7b..d5c727e 100644 (file)
@@ -75,6 +75,7 @@ OC_EXPORT bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri);
 
 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);
@@ -257,6 +258,22 @@ OC_EXPORT void OCPresencePayloadDestroy(OCPresencePayload* payload);
 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
index 4a0eea3..42aa770 100644 (file)
@@ -852,11 +852,21 @@ typedef enum
 {
     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;
 
 /**
@@ -952,8 +962,8 @@ typedef struct
     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
@@ -1201,7 +1211,7 @@ typedef struct
     char *uri;
 
     /** Resource Type */
-    char *type;
+    OCStringLL *type;
 
     /** Interface */
     OCStringLL *iface;
@@ -1242,7 +1252,7 @@ typedef struct
     char *sid;
     char* deviceName;
     char* specVersion;
-    char* dataModelVersion;
+    OCStringLL *dataModelVersions;
     OCStringLL *interfaces;
     OCStringLL *types;
 } OCDevicePayload;
@@ -1307,6 +1317,9 @@ typedef struct
     /** 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;
 
index 931e5f3..d04b9cd 100644 (file)
@@ -189,7 +189,10 @@ INLINE_API void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payloa
     }
     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)
@@ -233,7 +236,14 @@ INLINE_API void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
     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:");
index 13cf61b..970565a 100644 (file)
@@ -34,6 +34,7 @@
 #include <pthread.h>
 #endif
 #include <array>
+#include "oic_malloc.h"
 #include <getopt.h>
 #include "ocstack.h"
 #include "logger.h"
@@ -85,7 +86,7 @@ const char *supportUrl = "mySupportUrl";
 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
@@ -826,7 +827,7 @@ void DeleteDeviceInfo()
 {
     free (deviceInfo.deviceName);
     free (deviceInfo.specVersion);
-    free (deviceInfo.dataModleVersion);
+    OCFreeOCStringLL (deviceInfo.dataModelVersions);
 }
 
 bool DuplicateString(char** targetString, const char* sourceString)
@@ -930,7 +931,7 @@ OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerNa
     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))
     {
@@ -940,7 +941,9 @@ OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, con
     {
         return OC_STACK_ERROR;
     }
-    if(!DuplicateString(&deviceInfo.dataModleVersion, dataModleVersion))
+    OCFreeOCStringLL(deviceInfo.dataModelVersions);
+    deviceInfo.dataModelVersions = OCCreateOCStringLL(dataModelVersions);
+    if (!deviceInfo.dataModelVersions)
     {
         return OC_STACK_ERROR;
     }
@@ -1064,7 +1067,7 @@ int main(int argc, char* argv[])
         exit (EXIT_FAILURE);
     }
 
-    registrationResult = SetDeviceInfo(deviceName, specVersion, dataModleVersion);
+    registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
 
     if (registrationResult != OC_STACK_OK)
     {
index 91ba8cb..0fcee04 100644 (file)
@@ -64,6 +64,7 @@ static OCConnectivityType ocConnType;
 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;
 
@@ -102,8 +103,8 @@ static void PrintUsage()
     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,
@@ -434,6 +435,12 @@ int parseClientResponse(OCClientResponse * clientResponse)
             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);
index 4195a6b..b5fc0ca 100644 (file)
@@ -29,6 +29,7 @@
 #include <signal.h>
 #include <pthread.h>
 #include <array>
+#include "oic_malloc.h"
 #include "ocstack.h"
 #include "logger.h"
 #include "ocpayload.h"
@@ -77,7 +78,7 @@ const char *supportUrl = "mySupportUrl";
 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
@@ -810,7 +811,7 @@ void DeleteDeviceInfo()
 {
     free (deviceInfo.deviceName);
     free (deviceInfo.specVersion);
-    free (deviceInfo.dataModleVersion);
+    OCFreeOCStringLL (deviceInfo.dataModelVersions);
 }
 
 bool DuplicateString(char** targetString, const char* sourceString)
@@ -914,7 +915,7 @@ OCStackResult SetPlatformInfo(const char* platformID, const char *manufacturerNa
     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))
     {
@@ -924,7 +925,9 @@ OCStackResult SetDeviceInfo(const char* deviceName, const char* specVersion, con
     {
         return OC_STACK_ERROR;
     }
-    if(!DuplicateString(&deviceInfo.dataModleVersion, dataModleVersion))
+    OCFreeOCStringLL(deviceInfo.dataModelVersions);
+    deviceInfo.dataModelVersions = OCCreateOCStringLL(dataModelVersions);
+    if (!deviceInfo.dataModelVersions)
     {
         return OC_STACK_ERROR;
     }
@@ -1029,7 +1032,7 @@ int main(int argc, char* argv[])
         exit (EXIT_FAILURE);
     }
 
-    registrationResult = SetDeviceInfo(deviceName, specVersion, dataModleVersion);
+    registrationResult = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
 
     if (registrationResult != OC_STACK_OK)
     {
index 09d3093..0af830f 100644 (file)
@@ -66,6 +66,7 @@ cp resource/oc_logger/include/targets/oc_ostream_logger.h %{DEST_INC_DIR}
 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}
index 636572a..2051f73 100644 (file)
@@ -155,7 +155,8 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                                     request->numRcvdVendorSpecificHeaderOptions,
                                     request->rcvdVendorSpecificHeaderOptions,
                                     OC_OBSERVE_NO_OPTION,
-                                    0);
+                                    0,
+                                    request->coapID);
                         if (result == OC_STACK_OK)
                         {
                             ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest,
@@ -376,7 +377,7 @@ OCStackResult AddObserver (const char         *resUri,
         return OC_STACK_RESOURCE_ERROR;
     }
 
-    if (!resUri || !token || !*token)
+    if (!resUri || !token)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -446,7 +447,7 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLen
 {
     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);
@@ -472,7 +473,7 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t token, uint8_t tokenLen
 
 OCStackResult DeleteObserverUsingToken (CAToken_t token, uint8_t tokenLength)
 {
-    if (!token || !*token)
+    if (!token)
     {
         return OC_STACK_INVALID_PARAM;
     }
index 8815d47..be9b080 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+// Required for strok_r
+#define _POSIX_C_SOURCE 200112L
 
+#include <stdio.h>
 #include "ocpayload.h"
 #include "octypes.h"
 #include <string.h>
@@ -30,6 +33,7 @@
 #include "rdpayload.h"
 
 #define TAG "OIC_RI_PAYLOAD"
+#define CSV_SEPARATOR ','
 
 static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val);
 
@@ -1281,6 +1285,84 @@ OCStringLL* CloneOCStringLL (OCStringLL* ll)
     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)
@@ -1590,7 +1672,7 @@ void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* 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);
@@ -1627,8 +1709,8 @@ OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
         goto exit;
     }
 
-    payload->dataModelVersion = OICStrdup(dmVer);
-    if (dmVer && !payload->dataModelVersion)
+    payload->dataModelVersions = OCCreateOCStringLL(dmVer);
+    if (!payload->dataModelVersions || (dmVer && !payload->dataModelVersions->value))
     {
         goto exit;
     }
@@ -1659,7 +1741,7 @@ void OCDevicePayloadDestroy(OCDevicePayload* payload)
     OICFree(payload->sid);
     OICFree(payload->deviceName);
     OICFree(payload->specVersion);
-    OICFree(payload->dataModelVersion);
+    OCFreeOCStringLL(payload->dataModelVersions);
     OCFreeOCStringLL(payload->types);
     OCFreeOCStringLL(payload->interfaces);
     OICFree(payload);
index 9b791ea..890b527 100644 (file)
@@ -38,6 +38,9 @@
 // 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,
@@ -229,7 +232,7 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *o
         [                                                       // 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",
@@ -269,8 +272,7 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *o
         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
@@ -335,15 +337,14 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *o
             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);
@@ -391,6 +392,7 @@ static int64_t OCConvertDevicePayload(OCDevicePayload *payload, uint8_t *outPayl
     }
     int64_t err = CborNoError;
     CborEncoder encoder;
+    char *dataModelVersions = 0;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
     CborEncoder repMap;
@@ -426,10 +428,20 @@ static int64_t OCConvertDevicePayload(OCDevicePayload *payload, uint8_t *outPayl
             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");
old mode 100755 (executable)
new mode 100644 (file)
index dfd1ec7..ef9dc8a
@@ -249,7 +249,7 @@ static OCStackResult OCParseDiscoveryPayload(OCPayload **outPayload, CborValue *
         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");
         }
 
@@ -445,13 +445,17 @@ static OCStackResult OCParseDevicePayload(OCPayload **outPayload, CborValue *roo
             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");
@@ -1187,17 +1191,21 @@ static OCStackResult OCParsePresencePayload(OCPayload **outPayload, CborValue *r
     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
index a4370f3..fc36619 100755 (executable)
@@ -755,13 +755,6 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
                     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;
@@ -776,8 +769,7 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
                 }
                 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);
@@ -786,8 +778,10 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
                             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);
@@ -873,15 +867,24 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
         }
         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);
             }
         }
     }
@@ -990,7 +993,8 @@ HandleDefaultDeviceEntityHandler (OCServerRequest *request)
                                         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
@@ -1054,7 +1058,8 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
                                         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)
@@ -1189,7 +1194,8 @@ HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
                                         request->numRcvdVendorSpecificHeaderOptions,
                                         request->rcvdVendorSpecificHeaderOptions,
                                         (OCObserveAction)request->observationOption,
-                                        (OCObservationId)0);
+                                        (OCObservationId)0,
+                                        request->coapID);
     if(result == OC_STACK_OK)
     {
         result = DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest);
@@ -1347,10 +1353,10 @@ void DeleteDeviceInfo()
     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)
@@ -1392,10 +1398,10 @@ 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;
@@ -1403,8 +1409,13 @@ static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
     }
     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;
index 592f27a..24f734f 100644 (file)
@@ -362,7 +362,8 @@ OCStackResult FormOCEntityHandlerRequest(
         uint8_t numVendorOptions,
         OCHeaderOption * vendorOptions,
         OCObserveAction observeAction,
-        OCObservationId observeID)
+        OCObservationId observeID,
+        uint16_t messageID)
 {
     if (entityHandlerRequest)
     {
@@ -373,6 +374,7 @@ OCStackResult FormOCEntityHandlerRequest(
         entityHandlerRequest->query = queryBuf;
         entityHandlerRequest->obsInfo.action = observeAction;
         entityHandlerRequest->obsInfo.obsId = observeID;
+        entityHandlerRequest->messageID = messageID;
 
         if(payload && payloadSize)
         {
@@ -419,49 +421,67 @@ void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
 
 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;
@@ -495,6 +515,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
 
     CopyDevAddrToEndpoint(&serverRequest->devAddr, &responseEndpoint);
 
+    responseInfo.info.messageId = serverRequest->coapID;
     responseInfo.info.resourceUri = serverRequest->resourceUrl;
     responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult, serverRequest->method);
 
@@ -514,6 +535,8 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
     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)
@@ -752,7 +775,6 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
                     (OCRepPayload*)newPayload);
         }
 
-
         (serverRequest->numResponses)--;
 
         if(serverRequest->numResponses == 0)
@@ -773,4 +795,3 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
 exit:
     return stackRet;
 }
-
index 405bc4d..ac14ccd 100644 (file)
@@ -519,7 +519,8 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
                                                 NULL, PAYLOAD_TYPE_REPRESENTATION,
                                                 NULL, 0, 0, NULL,
                                                 OC_OBSERVE_DEREGISTER,
-                                                observer->observeId);
+                                                observer->observeId,
+                                                0);
             if(result != OC_STACK_OK)
             {
                 return result;
@@ -570,7 +571,8 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
                                                     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;
@@ -1150,7 +1152,7 @@ void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* resp
 
             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;
@@ -2641,12 +2643,6 @@ OCStackResult OCDoResource(OCDoHandle *handle,
         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)
@@ -4404,7 +4400,11 @@ void insertResourceInterface(OCResource *resource, OCResourceInterface *newInter
             previous = pointer;
             pointer = pointer->next;
         }
-        previous->next = newInterface;
+
+        if (previous)
+        {
+            previous->next = newInterface;
+        }
     }
 }
 
index 0378852..3c817b4 100644 (file)
@@ -604,10 +604,6 @@ OCTagsPayload* OCCopyTagsResources(const char *deviceName, const unsigned char *
     if (id)
     {
         OICStrcpy((char*)tags->di.id, MAX_IDENTITY_SIZE, (char *)id);
-        if (!tags->di.id)
-        {
-            goto memory_allocation_failed;
-        }
     }
     if (baseURI)
     {
index b81a15b..dba1515 100644 (file)
@@ -49,7 +49,7 @@ std::string systemTime = "mySystemTime";
 //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;
@@ -77,7 +77,7 @@ void DeleteDeviceInfo()
 {
     delete[] deviceInfo.deviceName;
     delete[] deviceInfo.specVersion;
-    delete[] deviceInfo.dataModleVersion;
+    OCFreeOCStringLL(deviceInfo.dataModelVersions);
 }
 
 void DuplicateString(char ** targetString, std::string sourceString)
@@ -106,15 +106,15 @@ OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerNa
 }
 
 
-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;
 }
@@ -148,7 +148,7 @@ int main()
     }
 
 
-    result = SetDeviceInfo(deviceName, specVersion, dataModleVersion);
+    result = SetDeviceInfo(deviceName, specVersion, dataModelVersions);
     OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.wk.d");
     OCResourcePayloadAddStringLL(&deviceInfo.types, "oic.d.tv");
 
index dbc91ea..556b34c 100644 (file)
@@ -114,6 +114,9 @@ class DeviceResource : public Resource
             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)
             {
index 6bc6efe..c4aff50 100644 (file)
@@ -73,16 +73,12 @@ void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& re
 {
     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;
@@ -107,9 +103,9 @@ void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& re
         }
         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
             {
@@ -477,7 +473,7 @@ int main(int argc, char* argv[]) {
         OC::ModeType::Both,
         "0.0.0.0",
         0,
-        OC::QualityOfService::LowQos,
+        OC::QualityOfService::HighQos,
         &ps
     };
 
index c0b1c08..be9a117 100644 (file)
@@ -145,6 +145,8 @@ namespace OC
 
             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);
@@ -155,6 +157,8 @@ namespace OC
 
             void addResourceInterface(const std::string& str);
 
+            void addDataModelVersion(const std::string& str);
+
             bool emptyData() const;
 
             int numberOfAttributes() const;
@@ -496,6 +500,7 @@ namespace OC
             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;
     };
index 64ffa7e..538a134 100644 (file)
@@ -51,6 +51,7 @@ namespace OC
             m_resourceUri{},
             m_queryParameters{},
             m_requestHandlerFlag{},
+            m_messageID{},
             m_representation{},
             m_observationInfo{},
             m_headerOptions{},
@@ -182,11 +183,19 @@ namespace OC
             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;
@@ -214,6 +223,11 @@ namespace OC
             m_requestHandlerFlag = requestHandlerFlag;
         }
 
+        void setMessageID(int16_t messageID)
+        {
+            m_messageID = messageID;
+        }
+
         void setObservationInfo(const ObservationInfo& observationInfo)
         {
             m_observationInfo = observationInfo;
index ef9317f..2fd1c19 100644 (file)
@@ -59,6 +59,7 @@ void formResourceRequest(OCEntityHandlerFlag flag,
     {
         pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
         pRequest->setResourceHandle(entityHandlerRequest->resource);
+        pRequest->setMessageID(entityHandlerRequest->messageID);
     }
 
     if(flag & OC_REQUEST_FLAG)
index 8818821..06b2083 100644 (file)
@@ -82,9 +82,10 @@ namespace OC
         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);
@@ -757,6 +758,16 @@ namespace OC
         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();
@@ -777,7 +788,8 @@ namespace OC
         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;
         }
index 93f62e4..d5aad2e 100644 (file)
@@ -88,7 +88,7 @@ namespace OCPlatformTest
         delete[] deviceInfo.deviceName;
         DeleteStringLL(deviceInfo.types);
         delete[] deviceInfo.specVersion;
-        delete[] deviceInfo.dataModleVersion;
+        DeleteStringLL(deviceInfo.dataModelVersions);
     }
 
     void DuplicateString(char ** targetString, std::string sourceString)
@@ -750,7 +750,8 @@ namespace OCPlatformTest
         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));
     }
index 6e41e8f..5ce6acd 100644 (file)
@@ -52,7 +52,7 @@ namespace OCRepresentationEncodingTest
     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)
@@ -66,10 +66,14 @@ namespace OCRepresentationEncodingTest
                 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);
@@ -85,7 +89,7 @@ namespace OCRepresentationEncodingTest
         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);
@@ -99,7 +103,8 @@ namespace OCRepresentationEncodingTest
         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);
     }
index 3b9e711..ca6a9f1 100644 (file)
@@ -37,6 +37,12 @@ namespace OCResourceResponseTest
         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)
index 87518ac..fe63791 100644 (file)
@@ -39,7 +39,7 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH) \
                                        $(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 \
index 4d60705..06ed5c4 100644 (file)
@@ -31,7 +31,7 @@ mediator_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 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',
index f885fde..eb2ab43 100644 (file)
@@ -46,7 +46,7 @@ if target_os not in ['windows']:
 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',
index e9e79de..2a527b5 100644 (file)
@@ -35,12 +35,14 @@ void BMISensorResource::handleSetAttributesRequest(
     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();
 }
 
index 05980ab..2f6f857 100644 (file)
@@ -38,12 +38,14 @@ void DiscomfortIndexSensorResource::handleSetAttributesRequest(
     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();
 }
 
index eb4849a..48825cc 100644 (file)
@@ -103,12 +103,14 @@ class TestBundleResource: public BundleResource
         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();
         }
 };
@@ -126,12 +128,14 @@ class TestBundleResourceWithAttrs: public BundleResource
         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();
         }
 };
@@ -148,12 +152,14 @@ class TestSoftSensorResource: public SoftSensorResource
         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();
         }
 
index 4f39b21..6657014 100644 (file)
@@ -55,6 +55,7 @@ class TestBundleResource : public BundleResource
         RCSResourceAttributes handleGetAttributesRequest(
             const std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             return BundleResource::getAttributes();
         }
 
@@ -62,6 +63,7 @@ class TestBundleResource : public BundleResource
             const RCSResourceAttributes &value,
             const std::map< std::string, std::string > &queryParams)
         {
+            (void)queryParams;
             BundleResource::setAttributes(value);
         }
 };
index a8f9f8f..229de74 100644 (file)
@@ -553,7 +553,7 @@ class ClientController
                     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;
index 27c7dd4..0d91809 100755 (executable)
@@ -85,7 +85,7 @@ echo "Framework: Copying includes..."
 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
index 45a0f74..9026920 100755 (executable)
@@ -86,7 +86,7 @@ find $OUTDIR/objs -name "*.o" | xargs rm
 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
index 0f0fc35..4177f08 100644 (file)
@@ -1,5 +1,5 @@
 Name: iotivity
-Version: 1.1.0
+Version: 1.1.1
 Release: 0
 Summary: IoT Connectivity sponsored by the OIC
 Group: Network & Connectivity/Other